Apache Lucene open-source search software
LUCENE-7730: Better accuracy for the length normalization factor.
Adrien Grand06a6034d9bc8
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex df8d20d3b0c..404e923d5a2 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -63,6 +63,9 @@ Improvements* LUCENE-7489: Better storage of sparse doc-values fields with the defaultcodec. (Adrien Grand)+* LUCENE-7730: More accurate encoding of the length normalization factor+ thanks to the removal of index-time boosts. (Adrien Grand)+Optimizations* LUCENE-7416: BooleanQuery optimizes queries that have queries that occur bothdiff --git a/lucene/benchmark/src/test/org/apache/lucene/benchmark/quality/trecQRels.txt b/lucene/benchmark/src/test/org/apache/lucene/benchmark/quality/trecQRels.txtindex 183a7f473e4..16094e33ee9 100644--- a/lucene/benchmark/src/test/org/apache/lucene/benchmark/quality/trecQRels.txt+++ b/lucene/benchmark/src/test/org/apache/lucene/benchmark/quality/trecQRels.txt@@ -40,64 +40,64 @@0 0 fakedoc3 10 0 fakedoc4 1-0 0 doc18211 10 0 doc20192 1+0 0 doc18211 1+0 0 doc12431 1+0 0 doc5471 1+0 0 doc3462 1+0 0 doc3057 10 0 doc7401 1-0 0 doc11285 1-0 0 doc20647 1-0 0 doc3057 1-0 0 doc12431 1-0 0 doc4989 1-0 0 doc17324 10 0 doc4030 1-0 0 doc4290 1-0 0 doc3462 1+0 0 doc4290 1+0 0 doc17904 1+0 0 doc11285 1+0 0 doc20647 1+0 0 doc17324 1+0 0 doc7168 1+0 0 doc9011 1+0 0 doc4989 10 0 doc15313 1-0 0 doc10303 1-0 0 doc1893 1-0 0 doc5008 1+0 0 doc10303 10 0 doc14634 1-0 0 doc5471 1-0 0 doc17904 1-0 0 doc7168 1-0 0 doc21275 1-0 0 doc9011 1-0 0 doc17546 10 0 doc9102 1-0 0 doc13199 1+0 0 doc5008 1+0 0 doc1893 1+0 0 doc17546 1+0 0 doc13199 1+0 0 doc21275 1# --- m==1: precision_at_n and avg_precision are hurt, by unmarking relevant docs-1 0 doc9857 0-1 0 doc16846 1-1 0 doc4320 1-1 0 doc9501 0-1 0 doc10159 1-1 0 doc16642 1-1 0 doc17536 0-1 0 doc17571 1-1 0 doc18728 1-1 0 doc18828 1-1 0 doc19108 0-1 0 doc9940 1-1 0 doc11852 1-1 0 doc7430 0-1 0 doc19162 1-1 0 doc1743 1-1 0 doc2137 1-1 0 doc7611 1-1 0 doc8072 1-1 0 doc12764 1-1 0 doc2593 1-1 0 doc11088 1-1 0 doc931 1-1 0 doc7673 1-1 0 doc12941 1-1 0 doc11797 1-1 0 doc11831 1-1 0 doc13162 1-1 0 doc4423 1-1 0 doc5217 1+1 0 doc9857 0+1 0 doc16846 1+1 0 doc9940 1+1 0 doc11852 0+1 0 doc12764 1+1 0 doc11088 1+1 0 doc2137 0+1 0 doc7673 1+1 0 doc7611 1+1 0 doc8072 1+1 0 doc19162 0+1 0 doc12941 1+1 0 doc931 1+1 0 doc2593 0+1 0 doc5037 1+1 0 doc13162 1+1 0 doc5018 1+1 0 doc11797 1+1 0 doc11831 1+1 0 doc5217 1+1 0 doc15426 1+1 0 doc7228 1+1 0 doc15370 1+1 0 doc10159 1+1 0 doc4320 1+1 0 doc9501 1+1 0 doc16642 1+1 0 doc17536 1+1 0 doc17571 1+1 0 doc18728 1# ---- m==2: all precision, precision_at_n and recall are hurt.@@ -106,200 +106,200 @@2 0 fakedoc3 12 0 fakedoc4 1-2 0 doc3137 0-2 0 doc7142 0-2 0 doc13667 0-2 0 doc13171 0-2 0 doc13372 1-2 0 doc21415 1-2 0 doc16298 1-2 0 doc14957 1-2 0 doc153 1-2 0 doc16092 1-2 0 doc16096 1-2 0 doc21303 1-2 0 doc18681 1-2 0 doc20756 1-2 0 doc355 1-2 0 doc13395 1-2 0 doc5009 1-2 0 doc17164 1-2 0 doc13162 1-2 0 doc11757 1-2 0 doc9637 1-2 0 doc18087 1-2 0 doc4593 1-2 0 doc4677 1-2 0 doc20865 1-2 0 doc8556 1-2 0 doc2578 1-2 0 doc1163 1-2 0 doc3797 1-2 0 doc11094 1---3 0 doc19578 1-3 0 doc14860 1-3 0 doc7235 1-3 0 doc20590 1-3 0 doc17933 1-3 0 doc9384 1-3 0 doc10783 1-3 0 doc1963 1-3 0 doc18356 1-3 0 doc13254 1-3 0 doc18402 1-3 0 doc15241 1-3 0 doc3303 1-3 0 doc8868 1-3 0 doc18520 1-3 0 doc4650 1-3 0 doc4727 1-3 0 doc21518 1-3 0 doc5060 1-3 0 doc7587 1-3 0 doc2990 1-3 0 doc8042 1-3 0 doc6304 1-3 0 doc13223 1-3 0 doc1964 1-3 0 doc10597 1-3 0 doc21023 1-3 0 doc19057 1-3 0 doc14948 1-3 0 doc9692 1---4 0 doc2534 1-4 0 doc21388 1-4 0 doc20923 1-4 0 doc11547 1-4 0 doc19755 1-4 0 doc3793 1-4 0 doc6714 1-4 0 doc12722 1-4 0 doc5552 1-4 0 doc6810 1-4 0 doc16953 1-4 0 doc2527 1-4 0 doc5361 1-4 0 doc12353 1-4 0 doc7308 1-4 0 doc3836 1-4 0 doc2293 1-4 0 doc7348 1-4 0 doc17119 1-4 0 doc19331 1-4 0 doc3411 1-4 0 doc14643 1-4 0 doc9058 1-4 0 doc11099 1-4 0 doc12485 1-4 0 doc16432 1-4 0 doc10047 1-4 0 doc13788 1-4 0 doc117 1-4 0 doc638 1+2 0 doc3137 0+2 0 doc13667 0+2 0 doc7142 0+2 0 doc16298 0+2 0 doc13171 1+2 0 doc14957 1+2 0 doc5009 1+2 0 doc13372 1+2 0 doc17164 1+2 0 doc21303 1+2 0 doc18681 1+2 0 doc13162 1+2 0 doc20756 1+2 0 doc3797 1+2 0 doc20865 1+2 0 doc153 1+2 0 doc16092 1+2 0 doc16096 1+2 0 doc2578 1+2 0 doc21415 1+2 0 doc4593 1+2 0 doc4677 1+2 0 doc21088 1+2 0 doc8556 1+2 0 doc9637 1+2 0 doc344 1+2 0 doc355 1+2 0 doc13395 1+2 0 doc1163 1+2 0 doc11757 1+++3 0 doc7235 1+3 0 doc19578 1+3 0 doc17933 1+3 0 doc20590 1+3 0 doc14860 1+3 0 doc10783 1+3 0 doc15241 1+3 0 doc13223 1+3 0 doc1963 1+3 0 doc10597 1+3 0 doc6304 1+3 0 doc3303 1+3 0 doc13254 1+3 0 doc9384 1+3 0 doc18356 1+3 0 doc18402 1+3 0 doc18520 1+3 0 doc14948 1+3 0 doc5060 1+3 0 doc4650 1+3 0 doc4727 1+3 0 doc19057 1+3 0 doc8868 1+3 0 doc2990 1+3 0 doc21518 1+3 0 doc21023 1+3 0 doc7587 1+3 0 doc8042 1+3 0 doc1964 1+3 0 doc7124 1++++4 0 doc2534 1+4 0 doc6714 1+4 0 doc6810 1+4 0 doc21388 1+4 0 doc5361 1+4 0 doc7308 1+4 0 doc20923 1+4 0 doc12722 1+4 0 doc2527 1+4 0 doc7348 1+4 0 doc10047 1+4 0 doc5552 1+4 0 doc19755 1+4 0 doc13788 1+4 0 doc14643 1+4 0 doc11547 1+4 0 doc2293 1+4 0 doc3793 1+4 0 doc19331 1+4 0 doc3836 1+4 0 doc12353 1+4 0 doc11099 1+4 0 doc16432 1+4 0 doc117 1+4 0 doc16953 1+4 0 doc9058 1+4 0 doc3411 1+4 0 doc12485 1+4 0 doc17119 1+4 0 doc638 15 0 doc13181 1-5 0 doc169 1-5 0 doc5389 1-5 0 doc955 1-5 0 doc8573 1+5 0 doc169 1+5 0 doc8573 15 0 doc10242 1-5 0 doc4350 1-5 0 doc17417 15 0 doc11758 1-5 0 doc9197 1+5 0 doc955 1+5 0 doc9197 1+5 0 doc17417 1+5 0 doc5389 1+5 0 doc4350 1+5 0 doc3857 1+5 0 doc3204 15 0 doc10639 1-5 0 doc3857 1-5 0 doc10478 15 0 doc10262 1-5 0 doc2981 1-5 0 doc3204 1+5 0 doc2981 1+5 0 doc10478 15 0 doc17122 1+5 0 doc4065 15 0 doc17864 1-5 0 doc9298 1-5 0 doc4065 1-5 0 doc2492 1-5 0 doc18879 1-5 0 doc12199 1-5 0 doc5180 1+5 0 doc9298 1+5 0 doc6918 15 0 doc11528 1+5 0 doc12199 1+5 0 doc2492 1+5 0 doc18879 15 0 doc20190 1-5 0 doc6918 1-5 0 doc4665 1+5 0 doc4665 1+5 0 doc5180 1+5 0 doc9124 15 0 doc10195 1-5 0 doc3062 1----6 0 doc9507 1-6 0 doc15630 1-6 0 doc8469 1-6 0 doc11918 1-6 0 doc20482 1-6 0 doc20158 1-6 0 doc19831 1-6 0 doc8296 1-6 0 doc8930 1-6 0 doc16460 1-6 0 doc2577 1-6 0 doc15476 1-6 0 doc1767 1-6 0 doc689 1-6 0 doc16606 1-6 0 doc6149 1-6 0 doc18691 1-6 0 doc2208 1-6 0 doc3592 1-6 0 doc11199 1-6 0 doc16329 1-6 0 doc6007 1-6 0 doc15231 1-6 0 doc20622 1-6 0 doc21468 1-6 0 doc12230 1-6 0 doc5723 1-6 0 doc8120 1-6 0 doc8668 1-6 0 doc303 1-----7 0 doc7728 1-7 0 doc7693 1-7 0 doc21088 1-7 0 doc5017 1-7 0 doc10807 1-7 0 doc16204 1-7 0 doc2233 1-7 0 doc3632 1-7 0 doc4719 1-7 0 doc6477 1-7 0 doc6502 1-7 0 doc6709 1-7 0 doc7710 1-7 0 doc9193 1-7 0 doc9309 1-7 0 doc9789 1-7 0 doc10971 1-7 0 doc18059 1-7 0 doc19906 1-7 0 doc20089 1-7 0 doc20102 1-7 0 doc21040 1-7 0 doc21153 1-7 0 doc9147 1-7 0 doc9930 1-7 0 doc19763 1-7 0 doc1559 1-7 0 doc21248 1-7 0 doc17945 1-7 0 doc526 1++++6 0 doc15630 1+6 0 doc9507 1+6 0 doc8469 1+6 0 doc20158 1+6 0 doc20482 1+6 0 doc1767 1+6 0 doc5723 1+6 0 doc12230 1+6 0 doc2577 1+6 0 doc11918 1+6 0 doc6007 1+6 0 doc20622 1+6 0 doc15231 1+6 0 doc21468 1+6 0 doc8296 1+6 0 doc16606 1+6 0 doc18691 1+6 0 doc6149 1+6 0 doc19831 1+6 0 doc8930 1+6 0 doc2208 1+6 0 doc16460 1+6 0 doc689 1+6 0 doc303 1+6 0 doc8120 1+6 0 doc11199 1+6 0 doc3592 1+6 0 doc8668 1+6 0 doc15476 1+6 0 doc7693 1++++7 0 doc7693 1+7 0 doc7728 1+7 0 doc21088 1+7 0 doc19763 1+7 0 doc19906 1+7 0 doc16204 1+7 0 doc4719 1+7 0 doc18059 1+7 0 doc9147 1+7 0 doc9930 1+7 0 doc6477 1+7 0 doc21040 1+7 0 doc2233 1+7 0 doc6709 1+7 0 doc7710 1+7 0 doc9789 1+7 0 doc10971 1+7 0 doc20102 1+7 0 doc5017 1+7 0 doc3632 1+7 0 doc6502 1+7 0 doc9193 1+7 0 doc9309 1+7 0 doc21153 1+7 0 doc526 1+7 0 doc20089 1+7 0 doc10807 1+7 0 doc1559 1+7 0 doc21248 1+7 0 doc15559 1# --- m==0: avg_precision and recall are hurt, by marking fake docs as relevant@@ -309,71 +309,71 @@8 0 fakedoc3 18 0 fakedoc4 1-8 0 doc16299 1-8 0 doc1662 1-8 0 doc4585 1-8 0 doc12315 1-8 0 doc16266 1-8 0 doc13136 1-8 0 doc19212 1-8 0 doc7086 1-8 0 doc7062 1-8 0 doc6134 1-8 0 doc13953 1-8 0 doc16264 1-8 0 doc2494 1-8 0 doc10636 1-8 0 doc10894 1-8 0 doc6844 1-8 0 doc674 1-8 0 doc13520 1-8 0 doc344 1-8 0 doc2896 1-8 0 doc11871 1-8 0 doc1862 1-8 0 doc16728 1-8 0 doc10308 1-8 0 doc2227 1-8 0 doc13167 1-8 0 doc20607 1-8 0 doc9670 1-8 0 doc1566 1-8 0 doc17885 1+8 0 doc1662 1+8 0 doc12315 1+8 0 doc16299 1+8 0 doc19212 1+8 0 doc2494 1+8 0 doc13520 1+8 0 doc13136 1+8 0 doc7086 1+8 0 doc674 1+8 0 doc16266 1+8 0 doc10894 1+8 0 doc4585 1+8 0 doc6134 1+8 0 doc7062 1+8 0 doc13953 1+8 0 doc2227 1+8 0 doc20607 1+8 0 doc344 1+8 0 doc16264 1+8 0 doc13167 1+8 0 doc2896 1+8 0 doc11871 1+8 0 doc6844 1+8 0 doc10636 1+8 0 doc9670 1+8 0 doc10180 1+8 0 doc1862 1+8 0 doc10308 1+8 0 doc16728 1+8 0 doc15794 1# ---- m==1: precision_at_n and avg_precision are hurt, by unmarking relevant docs-9 0 doc1990 0-9 0 doc9342 1-9 0 doc19427 1-9 0 doc12432 0-9 0 doc13480 1-9 0 doc3322 1-9 0 doc16044 1-9 0 doc266 0-9 0 doc3437 1-9 0 doc5370 1-9 0 doc10314 1-9 0 doc4892 1-9 0 doc5763 0-9 0 doc14045 1-9 0 doc1090 1-9 0 doc7437 1-9 0 doc5822 1-9 0 doc4285 1-9 0 doc17119 1-9 0 doc21001 1-9 0 doc4337 1-9 0 doc5967 1-9 0 doc10214 1-9 0 doc12001 1-9 0 doc18553 1-9 0 doc12116 1-9 0 doc5064 1-9 0 doc5018 1-9 0 doc5037 1-9 0 doc8025 1+9 0 doc1990 0+9 0 doc4892 1+9 0 doc9342 1+9 0 doc12432 0+9 0 doc13480 1+9 0 doc19427 1+9 0 doc12116 1+9 0 doc5064 0+9 0 doc14045 1+9 0 doc4285 1+9 0 doc5822 1+9 0 doc3322 1+9 0 doc5763 1+9 0 doc3437 0+9 0 doc5370 1+9 0 doc10314 1+9 0 doc16044 1+9 0 doc18553 1+9 0 doc5037 1+9 0 doc7437 1+9 0 doc12001 1+9 0 doc5018 1+9 0 doc1090 1+9 0 doc266 1+9 0 doc17894 1+9 0 doc17119 1+9 0 doc4337 1+9 0 doc5967 1+9 0 doc10214 1+9 0 doc20647 1# ---- m==2: all precision, precision_at_n and recall are hurt.@@ -384,200 +384,200 @@10 0 fakedoc4 110 0 doc16087 0-10 0 doc19943 0-10 0 doc5958 0-10 0 doc6510 0-10 0 doc4354 1-10 0 doc17218 1-10 0 doc6964 1-10 0 doc10270 1+10 0 doc17218 0+10 0 doc10270 0+10 0 doc16743 0+10 0 doc19943 1+10 0 doc16729 1+10 0 doc16761 1+10 0 doc4354 110 0 doc18321 1+10 0 doc5958 1+10 0 doc6510 1+10 0 doc7357 1+10 0 doc2534 1+10 0 doc6964 110 0 doc14893 1-10 0 doc16743 1-10 0 doc7357 1-10 0 doc2534 110 0 doc18497 1-10 0 doc16729 1-10 0 doc16761 1-10 0 doc8933 1-10 0 doc15769 110 0 doc14948 1+10 0 doc8933 1+10 0 doc14935 110 0 doc10818 1+10 0 doc7891 110 0 doc11819 1-10 0 doc7891 1-10 0 doc14935 1+10 0 doc7235 1+10 0 doc15769 110 0 doc14954 1-10 0 doc9897 1-10 0 doc6930 1-10 0 doc7235 1+10 0 doc9897 110 0 doc15559 1-10 0 doc6621 110 0 doc11214 1+10 0 doc5348 1+10 0 doc6930 1+11 0 doc8593 111 0 doc11943 1-11 0 doc9705 1-11 0 doc286 1+11 0 doc8800 1+11 0 doc286 111 0 doc17916 111 0 doc17918 1-11 0 doc1574 1+11 0 doc9705 1+11 0 doc1574 111 0 doc10180 1-11 0 doc1893 1+11 0 doc9337 1+11 0 doc11869 1+11 0 doc5194 111 0 doc11189 1-11 0 doc8593 1-11 0 doc3188 1-11 0 doc8800 1-11 0 doc9337 1+11 0 doc1893 111 0 doc19213 1-11 0 doc8735 1-11 0 doc5194 1-11 0 doc3552 1+11 0 doc3188 1+11 0 doc8735 1+11 0 doc18580 111 0 doc16030 1+11 0 doc3552 111 0 doc10195 1+11 0 doc209 1+11 0 doc5792 1+11 0 doc8715 111 0 doc17702 1-11 0 doc209 1-11 0 doc11869 1-11 0 doc5008 1-11 0 doc5792 1-11 0 doc1990 1-11 0 doc3393 1+11 0 doc3166 1+11 0 doc1990 1+11 0 doc3393 111 0 doc19027 1-11 0 doc18580 1-11 0 doc8715 1-11 0 doc12753 1+11 0 doc5008 1+12 0 doc6544 112 0 doc10640 1-12 0 doc6544 1-12 0 doc4305 1-12 0 doc10760 112 0 doc18198 1-12 0 doc10881 1-12 0 doc128 1+12 0 doc4305 1+12 0 doc2444 112 0 doc12192 1-12 0 doc2444 1-12 0 doc11639 1-12 0 doc2911 1-12 0 doc1884 1-12 0 doc2698 1-12 0 doc3552 1+12 0 doc10760 1+12 0 doc10881 1+12 0 doc128 1+12 0 doc1884 112 0 doc18704 1-12 0 doc7652 1-12 0 doc9187 1-12 0 doc3131 1-12 0 doc2277 1-12 0 doc2589 1-12 0 doc3747 1-12 0 doc3813 1-12 0 doc5222 1-12 0 doc6023 1-12 0 doc6624 1-12 0 doc7655 1-12 0 doc9205 1-12 0 doc12062 1+12 0 doc11639 1+12 0 doc3131 1+12 0 doc2698 1+12 0 doc3552 1+12 0 doc2911 1+12 0 doc7652 1+12 0 doc20524 1+12 0 doc9187 1+12 0 doc2277 112 0 doc15504 1-12 0 doc16329 1+12 0 doc2589 1+12 0 doc5222 1+12 0 doc3747 1+12 0 doc6624 1+12 0 doc9205 1+12 0 doc12062 1+12 0 doc3813 1+12 0 doc6023 1+12 0 doc7655 113 0 doc16347 1-13 0 doc1866 1+13 0 doc8695 1+13 0 doc4948 1+13 0 doc8554 113 0 doc13431 1-13 0 doc4948 1+13 0 doc1866 113 0 doc13989 1+13 0 doc2100 113 0 doc21565 1-13 0 doc8554 1-13 0 doc8695 1-13 0 doc6764 1-13 0 doc2408 1-13 0 doc5605 1-13 0 doc42 1+13 0 doc42 1+13 0 doc2408 113 0 doc15794 1+13 0 doc6764 1+13 0 doc3980 113 0 doc17135 1+13 0 doc5605 1+13 0 doc7783 1+13 0 doc5967 113 0 doc14847 1-13 0 doc3980 1-13 0 doc2592 1-13 0 doc5967 1-13 0 doc2100 113 0 doc10947 1-13 0 doc4557 1-13 0 doc2492 1-13 0 doc7783 1-13 0 doc8025 1-13 0 doc355 1-13 0 doc17170 1-13 0 doc14595 113 0 doc16894 1-13 0 doc5822 1+13 0 doc355 1+13 0 doc14595 1+13 0 doc8977 1+13 0 doc2592 1+13 0 doc4557 1+13 0 doc8025 1+13 0 doc2492 113 0 doc11088 1----14 0 doc17172 1-14 0 doc17210 1-14 0 doc5044 1-14 0 doc4627 1-14 0 doc4683 1-14 0 doc15126 1-14 0 doc4538 1-14 0 doc273 1-14 0 doc19585 1-14 0 doc16078 1-14 0 doc4529 1-14 0 doc4186 1-14 0 doc12961 1-14 0 doc19217 1-14 0 doc5670 1-14 0 doc1699 1-14 0 doc4716 1-14 0 doc12644 1-14 0 doc18387 1-14 0 doc336 1-14 0 doc16130 1-14 0 doc18718 1-14 0 doc12527 1-14 0 doc11797 1-14 0 doc11831 1-14 0 doc7538 1-14 0 doc17259 1-14 0 doc18724 1-14 0 doc19330 1-14 0 doc19206 1----15 0 doc12198 1-15 0 doc20371 1-15 0 doc2947 1-15 0 doc10750 1-15 0 doc7239 1-15 0 doc14189 1-15 0 doc19474 1-15 0 doc14776 1-15 0 doc21270 1-15 0 doc6387 1-15 0 doc12908 1-15 0 doc9573 1-15 0 doc17102 1-15 0 doc21482 1-15 0 doc6524 1-15 0 doc18034 1-15 0 doc1358 1-15 0 doc13147 1-15 0 doc17731 1-15 0 doc12890 1-15 0 doc20887 1-15 0 doc19508 1-15 0 doc18498 1-15 0 doc20642 1-15 0 doc19878 1-15 0 doc6556 1-15 0 doc10272 1-15 0 doc5720 1-15 0 doc17578 1-15 0 doc17164 1+13 0 doc1844 1++++14 0 doc17172 1+14 0 doc17210 1+14 0 doc4627 1+14 0 doc4683 1+14 0 doc15126 1+14 0 doc273 1+14 0 doc4716 1+14 0 doc4538 1+14 0 doc4529 1+14 0 doc19206 1+14 0 doc5044 1+14 0 doc12961 1+14 0 doc16078 1+14 0 doc19585 1+14 0 doc12527 1+14 0 doc19217 1+14 0 doc19330 1+14 0 doc5670 1+14 0 doc1699 1+14 0 doc11797 1+14 0 doc11831 1+14 0 doc17259 1+14 0 doc18387 1+14 0 doc7538 1+14 0 doc336 1+14 0 doc18718 1+14 0 doc4186 1+14 0 doc18724 1+14 0 doc18356 1+14 0 doc12644 1++++15 0 doc12198 1+15 0 doc20371 1+15 0 doc1358 1+15 0 doc20887 1+15 0 doc14189 1+15 0 doc14776 1+15 0 doc21270 1+15 0 doc13147 1+15 0 doc2947 1+15 0 doc7239 1+15 0 doc19474 1+15 0 doc12908 1+15 0 doc10750 1+15 0 doc19878 1+15 0 doc20642 1+15 0 doc19508 1+15 0 doc18034 1+15 0 doc6387 1+15 0 doc17102 1+15 0 doc6524 1+15 0 doc6556 1+15 0 doc9573 1+15 0 doc5720 1+15 0 doc10272 1+15 0 doc17164 1+15 0 doc15126 1+15 0 doc21482 1+15 0 doc4496 1+15 0 doc18498 1+15 0 doc10890 1# --- m==0: avg_precision and recall are hurt, by marking fake docs as relevant@@ -587,65 +587,70 @@16 0 fakedoc3 116 0 fakedoc4 1-16 0 doc4043 1-16 0 doc15370 1+16 0 doc4043 116 0 doc15426 1-16 0 doc1702 1+16 0 doc15370 1+16 0 doc1702 1+16 0 doc3446 1+16 0 doc3062 116 0 doc14985 1-16 0 doc3446 1+16 0 doc8224 116 0 doc16609 1+16 0 doc19032 1+16 0 doc7228 116 0 doc16134 1-16 0 doc3062 1-16 0 doc8224 1+16 0 doc5044 116 0 doc16493 1-16 0 doc15037 1+16 0 doc8545 116 0 doc12686 1-16 0 doc1710 1-16 0 doc19032 1-16 0 doc8545 1-16 0 doc5044 1-16 0 doc17894 1-16 0 doc7228 1-16 0 doc7373 1-16 0 doc9064 1-16 0 doc13161 1-16 0 doc3166 1+16 0 doc1710 1+16 0 doc15037 1+16 0 doc9064 116 0 doc19297 1+16 0 doc3281 1+16 0 doc3166 116 0 doc15499 1+16 0 doc17894 1+16 0 doc13161 1+16 0 doc13619 1+16 0 doc7373 1+16 0 doc15411 1+16 0 doc10890 1+16 0 doc8977 1# --- m==1: precision_at_n and avg_precision are hurt, by unmarking relevant docs-17 0 doc3117 0-17 0 doc7477 0-17 0 doc7569 0-17 0 doc20667 0-17 0 doc20260 1-17 0 doc17355 1-17 0 doc11021 1-17 0 doc20934 1-17 0 doc552 1-17 0 doc20856 1-17 0 doc3524 1-17 0 doc17343 1-17 0 doc21055 1-17 0 doc19032 1-17 0 doc19786 1-17 0 doc9281 1-17 0 doc1695 1-17 0 doc15940 1-17 0 doc9215 1-17 0 doc8335 1-17 0 doc20936 1-17 0 doc6914 1-17 0 doc12122 1-17 0 doc6618 1-17 0 doc5049 1-17 0 doc450 1-17 0 doc19206 1-17 0 doc18823 1-17 0 doc5307 1-17 0 doc17295 1+17 0 doc7477 0+17 0 doc7569 0+17 0 doc3117 0+17 0 doc20667 0+17 0 doc20260 1+17 0 doc20934 1+17 0 doc17355 1+17 0 doc3524 1+17 0 doc11021 1+17 0 doc552 1+17 0 doc21055 1+17 0 doc19032 1+17 0 doc1695 1+17 0 doc12122 1+17 0 doc20856 1+17 0 doc9215 1+17 0 doc15940 1+17 0 doc5049 1+17 0 doc19786 1+17 0 doc9281 1+17 0 doc450 1+17 0 doc17343 1+17 0 doc20936 1+17 0 doc8335 1+17 0 doc5307 1+17 0 doc6618 1+17 0 doc1168 1+17 0 doc18823 1+17 0 doc19206 1+17 0 doc6914 1# ---- m==2: all precision, precision_at_n and recall are hurt.@@ -655,61 +660,66 @@18 0 fakedoc3 118 0 fakedoc4 1-18 0 doc8064 0-18 0 doc18142 0-18 0 doc19383 0-18 0 doc21151 0-18 0 doc4665 1-18 0 doc2897 1-18 0 doc6878 1-18 0 doc14507 1-18 0 doc2976 1-18 0 doc11757 1-18 0 doc12625 1-18 0 doc14908 1-18 0 doc12790 1-18 0 doc17915 1-18 0 doc11804 1-18 0 doc12935 1-18 0 doc8225 1-18 0 doc18011 1-18 0 doc10493 1-18 0 doc17922 1-18 0 doc1902 1-18 0 doc14049 1-18 0 doc1334 1-18 0 doc1168 1-18 0 doc4859 1-18 0 doc7124 1-18 0 doc9692 1-18 0 doc18402 1-18 0 doc9089 1-18 0 doc15375 1----19 0 doc2310 1-19 0 doc5267 1+18 0 doc8064 0+18 0 doc18142 0+18 0 doc19383 0+18 0 doc2897 0+18 0 doc21151 1+18 0 doc14507 1+18 0 doc12935 1+18 0 doc12790 1+18 0 doc4665 1+18 0 doc10493 1+18 0 doc2976 1+18 0 doc18011 1+18 0 doc1334 1+18 0 doc14908 1+18 0 doc1168 1+18 0 doc15375 1+18 0 doc18402 1+18 0 doc8225 1+18 0 doc11757 1+18 0 doc11804 1+18 0 doc6878 1+18 0 doc12625 1+18 0 doc4859 1+18 0 doc5348 1+18 0 doc9089 1+18 0 doc14049 1+18 0 doc17922 1+18 0 doc1902 1+18 0 doc17915 1+18 0 doc7124 1++++19 0 doc2310 1+19 0 doc5267 119 0 doc15666 1-19 0 doc10803 1-19 0 doc4900 1+19 0 doc7925 1+19 0 doc4900 119 0 doc11435 1-19 0 doc7925 1-19 0 doc7652 1+19 0 doc10803 1+19 0 doc7652 1+19 0 doc19546 119 0 doc18561 1+19 0 doc9163 1+19 0 doc8869 119 0 doc12733 1+19 0 doc2444 1+19 0 doc7194 119 0 doc10634 1-19 0 doc19546 1-19 0 doc7194 1-19 0 doc529 1-19 0 doc9163 1-19 0 doc8869 1-19 0 doc2444 1-19 0 doc5605 1-19 0 doc5051 1-19 0 doc10881 1-19 0 doc4496 1-19 0 doc3979 1-19 0 doc8419 1-19 0 doc9431 1+19 0 doc529 1+19 0 doc8419 119 0 doc16235 1+19 0 doc4496 1+19 0 doc5051 1+19 0 doc5605 1+19 0 doc3979 1+19 0 doc9431 1+19 0 doc10881 1+19 0 doc12527 1+19 0 doc4804 1+19 0 doc4494 1+19 0 doc8833 1+19 0 doc732 1diff --git a/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java b/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.javaindex ba65629300c..ca384aebc71 100644--- a/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java+++ b/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java@@ -603,7 +603,7 @@ final class DefaultIndexingChain extends DocConsumer {// PerField.invert to allow for later downgrading of the index options:fi.setIndexOptions(fieldType.indexOptions());- fp = new PerField(fi, invert);+ fp = new PerField(docWriter.getIndexCreatedVersionMajor(), fi, invert);fp.next = fieldHash[hashPos];fieldHash[hashPos] = fp;totalFieldCount++;@@ -633,6 +633,7 @@ final class DefaultIndexingChain extends DocConsumer {/** NOTE: not static: accesses at least docState, termsHash. */private final class PerField implements Comparable<PerField> {+ final int indexCreatedVersionMajor;final FieldInfo fieldInfo;final Similarity similarity;@@ -659,7 +660,8 @@ final class DefaultIndexingChain extends DocConsumer {// reusedTokenStream tokenStream;- public PerField(FieldInfo fieldInfo, boolean invert) {+ public PerField(int indexCreatedVersionMajor, FieldInfo fieldInfo, boolean invert) {+ this.indexCreatedVersionMajor = indexCreatedVersionMajor;this.fieldInfo = fieldInfo;similarity = docState.similarity;if (invert) {@@ -668,7 +670,7 @@ final class DefaultIndexingChain extends DocConsumer {}void setInvertState() {- invertState = new FieldInvertState(fieldInfo.name);+ invertState = new FieldInvertState(indexCreatedVersionMajor, fieldInfo.name);termsHashPerField = termsHash.addField(invertState, fieldInfo);if (fieldInfo.omitsNorms() == false) {assert norms == null;diff --git a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.javaindex ed50650f86e..c929ba239c2 100644--- a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java+++ b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java@@ -193,6 +193,10 @@ class DocumentsWriterPerThread {return fieldInfos;}+ public int getIndexCreatedVersionMajor() {+ return indexWriter.segmentInfos.getIndexCreatedVersionMajor();+ }+final void testPoint(String message) {if (enableTestPoints) {assert infoStream.isEnabled("TP"); // don't enable unless you need them.diff --git a/lucene/core/src/java/org/apache/lucene/index/FieldInvertState.java b/lucene/core/src/java/org/apache/lucene/index/FieldInvertState.javaindex 1da02b24f4c..f93edde3991 100644--- a/lucene/core/src/java/org/apache/lucene/index/FieldInvertState.java+++ b/lucene/core/src/java/org/apache/lucene/index/FieldInvertState.java@@ -31,7 +31,8 @@ import org.apache.lucene.util.AttributeSource;* @lucene.experimental*/public final class FieldInvertState {- String name;+ final int indexCreatedVersionMajor;+ final String name;int position;int length;int numOverlap;@@ -50,14 +51,15 @@ public final class FieldInvertState {/** Creates {code FieldInvertState} for the specified* field name. */- public FieldInvertState(String name) {+ public FieldInvertState(int indexCreatedVersionMajor, String name) {+ this.indexCreatedVersionMajor = indexCreatedVersionMajor;this.name = name;}/** Creates {code FieldInvertState} for the specified* field name and values for all fields. */- public FieldInvertState(String name, int position, int length, int numOverlap, int offset) {- this.name = name;+ public FieldInvertState(int indexCreatedVersionMajor, String name, int position, int length, int numOverlap, int offset) {+ this(indexCreatedVersionMajor, name);this.position = position;this.length = length;this.numOverlap = numOverlap;@@ -164,4 +166,11 @@ public final class FieldInvertState {public String getName() {return name;}++ /**+ * Return the version that was used to create the index, or 6 if it was created before 7.0.+ */+ public int getIndexCreatedVersionMajor() {+ return indexCreatedVersionMajor;+ }}diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.javaindex 74978fd4dd9..e693b2b9946 100644--- a/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java@@ -96,20 +96,6 @@ public class BM25Similarity extends Similarity {}}- /** The default implementation encodes <code>1 / sqrt(length)</code>- * with {@link SmallFloat#floatToByte315(float)}. This is compatible with- * Lucene's historic implementation: {@link ClassicSimilarity}. If you- * change this, then you should change {@link #decodeNormValue(byte)} to match. */- protected byte encodeNormValue(int fieldLength) {- return SmallFloat.floatToByte315((float) (1 / Math.sqrt(fieldLength)));- }-- /** The default implementation returns <code>1 / f<sup>2</sup></code>- * where <code>f</code> is {@link SmallFloat#byte315ToFloat(byte)}. */- protected float decodeNormValue(byte b) {- return NORM_TABLE[b & 0xFF];- }-/*** True if overlap tokens (tokens with a position of increment of zero) are* discounted from the document's length.@@ -132,21 +118,31 @@ public class BM25Similarity extends Similarity {}/** Cache of decoded bytes. */- private static final float[] NORM_TABLE = new float[256];+ private static final float[] OLD_LENGTH_TABLE = new float[256];+ private static final float[] LENGTH_TABLE = new float[256];static {for (int i = 1; i < 256; i++) {float f = SmallFloat.byte315ToFloat((byte)i);- NORM_TABLE[i] = 1.0f / (f*f);+ OLD_LENGTH_TABLE[i] = 1.0f / (f*f);+ }+ OLD_LENGTH_TABLE[0] = 1.0f / OLD_LENGTH_TABLE[255]; // otherwise inf++ for (int i = 0; i < 256; i++) {+ LENGTH_TABLE[i] = SmallFloat.byte4ToInt((byte) i);}- NORM_TABLE[0] = 1.0f / NORM_TABLE[255]; // otherwise inf}@Overridepublic final long computeNorm(FieldInvertState state) {final int numTerms = discountOverlaps ? state.getLength() - state.getNumOverlap() : state.getLength();- return encodeNormValue(numTerms);+ int indexCreatedVersionMajor = state.getIndexCreatedVersionMajor();+ if (indexCreatedVersionMajor >= 7) {+ return SmallFloat.intToByte4(numTerms);+ } else {+ return SmallFloat.floatToByte315((float) (1 / Math.sqrt(numTerms)));+ }}/**@@ -207,34 +203,43 @@ public class BM25Similarity extends Similarity {@Overridepublic final SimWeight computeWeight(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) {Explanation idf = termStats.length == 1 ? idfExplain(collectionStats, termStats[0]) : idfExplain(collectionStats, termStats);-float avgdl = avgFieldLength(collectionStats);- // compute freq-independent part of bm25 equation across all norm values- float cache[] = new float[256];+ float[] oldCache = new float[256];+ float[] cache = new float[256];for (int i = 0; i < cache.length; i++) {- cache[i] = k1 * ((1 - b) + b * decodeNormValue((byte)i) / avgdl);+ oldCache[i] = k1 * ((1 - b) + b * OLD_LENGTH_TABLE[i] / avgdl);+ cache[i] = k1 * ((1 - b) + b * LENGTH_TABLE[i] / avgdl);}- return new BM25Stats(collectionStats.field(), boost, idf, avgdl, cache);+ return new BM25Stats(collectionStats.field(), boost, idf, avgdl, oldCache, cache);}@Overridepublic final SimScorer simScorer(SimWeight stats, LeafReaderContext context) throws IOException {BM25Stats bm25stats = (BM25Stats) stats;- return new BM25DocScorer(bm25stats, context.reader().getNormValues(bm25stats.field));+ return new BM25DocScorer(bm25stats, context.reader().getMetaData().getCreatedVersionMajor(), context.reader().getNormValues(bm25stats.field));}private class BM25DocScorer extends SimScorer {private final BM25Stats stats;private final float weightValue; // boost * idf * (k1 + 1)private final NumericDocValues norms;+ /** precomputed cache for all length values */+ private final float[] lengthCache;+ /** precomputed norm[256] with k1 * ((1 - b) + b * dl / avgdl) */private final float[] cache;- BM25DocScorer(BM25Stats stats, NumericDocValues norms) throws IOException {+ BM25DocScorer(BM25Stats stats, int indexCreatedVersionMajor, NumericDocValues norms) throws IOException {this.stats = stats;this.weightValue = stats.weight * (k1 + 1);- this.cache = stats.cache;this.norms = norms;+ if (indexCreatedVersionMajor >= 7) {+ lengthCache = LENGTH_TABLE;+ cache = stats.cache;+ } else {+ lengthCache = OLD_LENGTH_TABLE;+ cache = stats.oldCache;+ }}@Override@@ -245,7 +250,7 @@ public class BM25Similarity extends Similarity {norm = k1;} else {if (norms.advanceExact(doc)) {- norm = cache[(byte)norms.longValue() & 0xFF];+ norm = cache[((byte) norms.longValue()) & 0xFF];} else {norm = cache[0];}@@ -255,7 +260,7 @@ public class BM25Similarity extends Similarity {@Overridepublic Explanation explain(int doc, Explanation freq) throws IOException {- return explainScore(doc, freq, stats, norms);+ return explainScore(doc, freq, stats, norms, lengthCache);}@Override@@ -281,21 +286,23 @@ public class BM25Similarity extends Similarity {private final float weight;/** field name, for pulling norms */private final String field;- /** precomputed norm[256] with k1 * ((1 - b) + b * dl / avgdl) */- private final float cache[];+ /** precomputed norm[256] with k1 * ((1 - b) + b * dl / avgdl)+ * for both OLD_LENGTH_TABLE and LENGTH_TABLE */+ private final float[] oldCache, cache;- BM25Stats(String field, float boost, Explanation idf, float avgdl, float cache[]) {+ BM25Stats(String field, float boost, Explanation idf, float avgdl, float[] oldCache, float[] cache) {this.field = field;this.boost = boost;this.idf = idf;this.avgdl = avgdl;- this.cache = cache;this.weight = idf.getValue() * boost;+ this.oldCache = oldCache;+ this.cache = cache;}}- private Explanation explainTFNorm(int doc, Explanation freq, BM25Stats stats, NumericDocValues norms) throws IOException {+ private Explanation explainTFNorm(int doc, Explanation freq, BM25Stats stats, NumericDocValues norms, float[] lengthCache) throws IOException {List<Explanation> subs = new ArrayList<>();subs.add(freq);subs.add(Explanation.match(k1, "parameter k1"));@@ -311,7 +318,7 @@ public class BM25Similarity extends Similarity {} else {norm = 0;}- float doclen = decodeNormValue(norm);+ float doclen = lengthCache[norm & 0xff];subs.add(Explanation.match(b, "parameter b"));subs.add(Explanation.match(stats.avgdl, "avgFieldLength"));subs.add(Explanation.match(doclen, "fieldLength"));@@ -321,13 +328,13 @@ public class BM25Similarity extends Similarity {}}- private Explanation explainScore(int doc, Explanation freq, BM25Stats stats, NumericDocValues norms) throws IOException {+ private Explanation explainScore(int doc, Explanation freq, BM25Stats stats, NumericDocValues norms, float[] lengthCache) throws IOException {Explanation boostExpl = Explanation.match(stats.boost, "boost");List<Explanation> subs = new ArrayList<>();if (boostExpl.getValue() != 1.0f)subs.add(boostExpl);subs.add(stats.idf);- Explanation tfNormExpl = explainTFNorm(doc, freq, stats, norms);+ Explanation tfNormExpl = explainTFNorm(doc, freq, stats, norms, lengthCache);subs.add(tfNormExpl);return Explanation.match(boostExpl.getValue() * stats.idf.getValue() * tfNormExpl.getValue(),diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/ClassicSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/ClassicSimilarity.javaindex f56575f0d4c..c3d36c3a922 100644--- a/lucene/core/src/java/org/apache/lucene/search/similarities/ClassicSimilarity.java+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/ClassicSimilarity.java@@ -17,91 +17,27 @@package org.apache.lucene.search.similarities;-import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.search.CollectionStatistics;import org.apache.lucene.search.Explanation;import org.apache.lucene.search.TermStatistics;import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.SmallFloat;/**- * Expert: Default scoring implementation which {@link #encodeNormValue(float)- * encodes} norm values as a single byte before being stored. At search time,- * the norm byte value is read from the index- * {@link org.apache.lucene.store.Directory directory} and- * {@link #decodeNormValue(long) decoded} back to a float <i>norm</i> value.- * This encoding/decoding, while reducing index size, comes with the price of- * precision loss - it is not guaranteed that <i>decode(encode(x)) = x</i>. For- * instance, <i>decode(encode(0.89)) = 0.875</i>.- * <p>- * Compression of norm values to a single byte saves memory at search time,- * because once a field is referenced at search time, its norms - for all- * documents - are maintained in memory.- * <p>- * The rationale supporting such lossy compression of norm values is that given- * the difficulty (and inaccuracy) of users to express their true information- * need by a query, only big differences matter. <br>- * <br>- * Last, note that search time is too late to modify this <i>norm</i> part of- * scoring, e.g. by using a different {@link Similarity} for search.+ * Expert: Historical scoring implementation. You might want to consider using+ * {@link BM25Similarity} instead, which is generally considered superior to+ * TF-IDF.*/public class ClassicSimilarity extends TFIDFSimilarity {-- /** Cache of decoded bytes. */- private static final float[] NORM_TABLE = new float[256];-- static {- for (int i = 0; i < 256; i++) {- NORM_TABLE[i] = SmallFloat.byte315ToFloat((byte)i);- }- }/** Sole constructor: parameter-free */public ClassicSimilarity() {}-- /**- * Encodes a normalization factor for storage in an index.- * <p>- * The encoding uses a three-bit mantissa, a five-bit exponent, and the- * zero-exponent point at 15, thus representing values from around 7x10^9 to- * 2x10^-9 with about one significant decimal digit of accuracy. Zero is also- * represented. Negative numbers are rounded up to zero. Values too large to- * represent are rounded down to the largest representable value. Positive- * values too small to represent are rounded up to the smallest positive- * representable value.- *- * @see org.apache.lucene.util.SmallFloat- */- @Override- public final long encodeNormValue(float f) {- return SmallFloat.floatToByte315(f);- }-- /**- * Decodes the norm value, assuming it is a single byte.- *- * @see #encodeNormValue(float)- */- @Override- public final float decodeNormValue(long norm) {- return NORM_TABLE[(int) (norm & 0xFF)]; // & 0xFF maps negative bytes to positive above 127- }/** Implemented as- * <code>state.getBoost()*lengthNorm(numTerms)</code>, where- * <code>numTerms</code> is {@link FieldInvertState#getLength()} if {@link- * #setDiscountOverlaps} is false, else it's {@link- * FieldInvertState#getLength()} - {@link- * FieldInvertState#getNumOverlap()}.+ * <code>1/sqrt(length)</code>.** @lucene.experimental */@Override- public float lengthNorm(FieldInvertState state) {- final int numTerms;- if (discountOverlaps)- numTerms = state.getLength() - state.getNumOverlap();- else- numTerms = state.getLength();+ public float lengthNorm(int numTerms) {return (float) (1.0 / Math.sqrt(numTerms));}@@ -138,33 +74,6 @@ public class ClassicSimilarity extends TFIDFSimilarity {public float idf(long docFreq, long docCount) {return (float)(Math.log((docCount+1)/(double)(docFreq+1)) + 1.0);}-- /**- * True if overlap tokens (tokens with a position of increment of zero) are- * discounted from the document's length.- */- protected boolean discountOverlaps = true;-- /** Determines whether overlap tokens (Tokens with- * 0 position increment) are ignored when computing- * norm. By default this is true, meaning overlap- * tokens do not count when computing norms.- *- * @lucene.experimental- *- * @see #computeNorm- */- public void setDiscountOverlaps(boolean v) {- discountOverlaps = v;- }-- /**- * Returns true if overlap tokens are discounted from the document's length.- * @see #setDiscountOverlaps- */- public boolean getDiscountOverlaps() {- return discountOverlaps;- }@Overridepublic String toString() {diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java b/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.javaindex dbf8d45760c..fb34f07a97c 100644--- a/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java@@ -190,7 +190,8 @@ public abstract class SimilarityBase extends Similarity {}@Override- public SimScorer simScorer(SimWeight stats, LeafReaderContext context) throws IOException {+ public final SimScorer simScorer(SimWeight stats, LeafReaderContext context) throws IOException {+ int indexCreatedVersionMajor = context.reader().getMetaData().getCreatedVersionMajor();if (stats instanceof MultiSimilarity.MultiStats) {// a multi term query (e.g. phrase). return the summation,// scoring almost as if it were boolean query@@ -198,12 +199,12 @@ public abstract class SimilarityBase extends Similarity {SimScorer subScorers[] = new SimScorer[subStats.length];for (int i = 0; i < subScorers.length; i++) {BasicStats basicstats = (BasicStats) subStats[i];- subScorers[i] = new BasicSimScorer(basicstats, context.reader().getNormValues(basicstats.field));+ subScorers[i] = new BasicSimScorer(basicstats, indexCreatedVersionMajor, context.reader().getNormValues(basicstats.field));}return new MultiSimilarity.MultiSimScorer(subScorers);} else {BasicStats basicstats = (BasicStats) stats;- return new BasicSimScorer(basicstats, context.reader().getNormValues(basicstats.field));+ return new BasicSimScorer(basicstats, indexCreatedVersionMajor, context.reader().getNormValues(basicstats.field));}}@@ -216,40 +217,38 @@ public abstract class SimilarityBase extends Similarity {// ------------------------------ Norm handling ------------------------------- /** Norm to document length map. */- private static final float[] NORM_TABLE = new float[256];+ /** Cache of decoded bytes. */+ private static final float[] OLD_LENGTH_TABLE = new float[256];+ private static final float[] LENGTH_TABLE = new float[256];static {for (int i = 1; i < 256; i++) {- float floatNorm = SmallFloat.byte315ToFloat((byte)i);- NORM_TABLE[i] = 1.0f / (floatNorm * floatNorm);+ float f = SmallFloat.byte315ToFloat((byte)i);+ OLD_LENGTH_TABLE[i] = 1.0f / (f*f);+ }+ OLD_LENGTH_TABLE[0] = 1.0f / OLD_LENGTH_TABLE[255]; // otherwise inf++ for (int i = 0; i < 256; i++) {+ LENGTH_TABLE[i] = SmallFloat.byte4ToInt((byte) i);}- NORM_TABLE[0] = 1.0f / NORM_TABLE[255]; // otherwise inf}- /** Encodes the document length in the same way as {@link TFIDFSimilarity}. */+ /** Encodes the document length in the same way as {@link BM25Similarity}. */@Override- public long computeNorm(FieldInvertState state) {- final float numTerms;+ public final long computeNorm(FieldInvertState state) {+ final int numTerms;if (discountOverlaps)numTerms = state.getLength() - state.getNumOverlap();elsenumTerms = state.getLength();- return encodeNormValue(numTerms);- }-- /** Decodes a normalization factor (document length) stored in an index.- * @see #encodeNormValue(float)- */- protected float decodeNormValue(byte norm) {- return NORM_TABLE[norm & 0xFF]; // & 0xFF maps negative bytes to positive above 127- }-- /** Encodes the length to a byte via SmallFloat. */- protected byte encodeNormValue(float length) {- return SmallFloat.floatToByte315((float) (1 / Math.sqrt(length)));+ int indexCreatedVersionMajor = state.getIndexCreatedVersionMajor();+ if (indexCreatedVersionMajor >= 7) {+ return SmallFloat.intToByte4(numTerms);+ } else {+ return SmallFloat.floatToByte315((float) (1 / Math.sqrt(numTerms)));+ }}-+// ----------------------------- Static methods ------------------------------/** Returns the base two logarithm of {@code x}. */@@ -266,35 +265,37 @@ public abstract class SimilarityBase extends Similarity {* {@link SimilarityBase#explain(BasicStats, int, Explanation, float)},* respectively.*/- private class BasicSimScorer extends SimScorer {+ final class BasicSimScorer extends SimScorer {private final BasicStats stats;private final NumericDocValues norms;+ private final float[] normCache;- BasicSimScorer(BasicStats stats, NumericDocValues norms) throws IOException {+ BasicSimScorer(BasicStats stats, int indexCreatedVersionMajor, NumericDocValues norms) throws IOException {this.stats = stats;this.norms = norms;+ this.normCache = indexCreatedVersionMajor >= 7 ? LENGTH_TABLE : OLD_LENGTH_TABLE;}- private float getNormValue(int doc) throws IOException {+ float getLengthValue(int doc) throws IOException {if (norms == null) {return 1F;}if (norms.advanceExact(doc)) {- return decodeNormValue((byte) norms.longValue());+ return normCache[Byte.toUnsignedInt((byte) norms.longValue())];} else {- return decodeNormValue((byte) 0);+ return 0;}}@Overridepublic float score(int doc, float freq) throws IOException {// We have to supply something in case norms are omitted- return SimilarityBase.this.score(stats, freq, getNormValue(doc));+ return SimilarityBase.this.score(stats, freq, getLengthValue(doc));}@Overridepublic Explanation explain(int doc, Explanation freq) throws IOException {- return SimilarityBase.this.explain(stats, doc, freq, getNormValue(doc));+ return SimilarityBase.this.explain(stats, doc, freq, getLengthValue(doc));}@Overridediff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.javaindex 22465618689..14b3c3f8359 100644--- a/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java@@ -30,6 +30,7 @@ import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.PhraseQuery;import org.apache.lucene.search.TermStatistics;import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.SmallFloat;/**@@ -233,11 +234,6 @@ import org.apache.lucene.util.BytesRef;* And this is exactly what normalizing the query vector <i>V(q)</i>* provides: comparability (to a certain extent) of two or more queries.* </li>- *- * <li>Applying query normalization on the scores helps to keep the- * scores around the unit vector, hence preventing loss of score data- * because of floating point precision limitations.- * </li>* </ul>* </li>*@@ -379,13 +375,49 @@ import org.apache.lucene.util.BytesRef;* @see IndexSearcher#setSimilarity(Similarity)*/public abstract class TFIDFSimilarity extends Similarity {-++ /** Cache of decoded bytes. */+ static final float[] OLD_NORM_TABLE = new float[256];++ static {+ for (int i = 0; i < 256; i++) {+ OLD_NORM_TABLE[i] = SmallFloat.byte315ToFloat((byte)i);+ }+ }+/*** Sole constructor. (For invocation by subclass* constructors, typically implicit.)*/public TFIDFSimilarity() {}-++ /**+ * True if overlap tokens (tokens with a position of increment of zero) are+ * discounted from the document's length.+ */+ protected boolean discountOverlaps = true;++ /** Determines whether overlap tokens (Tokens with+ * 0 position increment) are ignored when computing+ * norm. By default this is true, meaning overlap+ * tokens do not count when computing norms.+ *+ * @lucene.experimental+ *+ * @see #computeNorm+ */+ public void setDiscountOverlaps(boolean v) {+ discountOverlaps = v;+ }++ /**+ * Returns true if overlap tokens are discounted from the document's length.+ * @see #setDiscountOverlaps+ */+ public boolean getDiscountOverlaps() {+ return discountOverlaps;+ }+/** Computes a score factor based on a term or phrase's frequency in a* document. This value is multiplied by the {@link #idf(long, long)}* factor for each term in the query and these products are then summed to@@ -471,30 +503,25 @@ public abstract class TFIDFSimilarity extends Similarity {/*** Compute an index-time normalization value for this field instance.- * <p>- * This value will be stored in a single byte lossy representation by- * {@link #encodeNormValue(float)}.*- * @param state statistics of the current field (such as length, boost, etc)- * @return an index-time normalization value+ * @param length the number of terms in the field, optionally {@link #setDiscountOverlaps(boolean) discounting overlaps}+ * @return a length normalization value*/- public abstract float lengthNorm(FieldInvertState state);+ public abstract float lengthNorm(int length);@Overridepublic final long computeNorm(FieldInvertState state) {- float normValue = lengthNorm(state);- return encodeNormValue(normValue);+ final int numTerms;+ if (discountOverlaps)+ numTerms = state.getLength() - state.getNumOverlap();+ else+ numTerms = state.getLength();+ if (state.getIndexCreatedVersionMajor() >= 7) {+ return SmallFloat.intToByte4(numTerms);+ } else {+ return SmallFloat.floatToByte315(lengthNorm(numTerms));+ }}-- /**- * Decodes a normalization factor stored in an index.- *- * @see #encodeNormValue(float)- */- public abstract float decodeNormValue(long norm);-- /** Encodes a normalization factor for storage in an index. */- public abstract long encodeNormValue(float f);/** Computes the amount of a sloppy phrase match, based on an edit distance.* This value is summed for each sloppy phrase match in a document to form@@ -529,24 +556,41 @@ public abstract class TFIDFSimilarity extends Similarity {final Explanation idf = termStats.length == 1? idfExplain(collectionStats, termStats[0]): idfExplain(collectionStats, termStats);- return new IDFStats(collectionStats.field(), boost, idf);+ float[] normTable = new float[256];+ for (int i = 1; i < 256; ++i) {+ int length = SmallFloat.byte4ToInt((byte) i);+ float norm = lengthNorm(length);+ normTable[i] = norm;+ }+ normTable[0] = 1f / normTable[255];+ return new IDFStats(collectionStats.field(), boost, idf, normTable);}@Overridepublic final SimScorer simScorer(SimWeight stats, LeafReaderContext context) throws IOException {IDFStats idfstats = (IDFStats) stats;- return new TFIDFSimScorer(idfstats, context.reader().getNormValues(idfstats.field));+ final float[] normTable;+ if (context.reader().getMetaData().getCreatedVersionMajor() >= 7) {+ // the norms only encode the length, we need a translation table that depends on how lengthNorm is implemented+ normTable = idfstats.normTable;+ } else {+ // the norm is directly encoded in the index+ normTable = OLD_NORM_TABLE;+ }+ return new TFIDFSimScorer(idfstats, context.reader().getNormValues(idfstats.field), normTable);}private final class TFIDFSimScorer extends SimScorer {private final IDFStats stats;private final float weightValue;private final NumericDocValues norms;+ private final float[] normTable;- TFIDFSimScorer(IDFStats stats, NumericDocValues norms) throws IOException {+ TFIDFSimScorer(IDFStats stats, NumericDocValues norms, float[] normTable) throws IOException {this.stats = stats;this.weightValue = stats.queryWeight;this.norms = norms;+ this.normTable = normTable;}@Override@@ -556,13 +600,13 @@ public abstract class TFIDFSimilarity extends Similarity {if (norms == null) {return raw;} else {- long normValue;+ float normValue;if (norms.advanceExact(doc)) {- normValue = norms.longValue();+ normValue = normTable[(int) (norms.longValue() & 0xFF)];} else {normValue = 0;}- return raw * decodeNormValue(normValue); // normalize for field+ return raw * normValue; // normalize for field}}@@ -578,35 +622,39 @@ public abstract class TFIDFSimilarity extends Similarity {@Overridepublic Explanation explain(int doc, Explanation freq) throws IOException {- return explainScore(doc, freq, stats, norms);+ return explainScore(doc, freq, stats, norms, normTable);}}/** Collection statistics for the TF-IDF model. The only statistic of interest* to this model is idf. */- private static class IDFStats extends SimWeight {+ static class IDFStats extends SimWeight {private final String field;/** The idf and its explanation */private final Explanation idf;private final float boost;private final float queryWeight;+ final float[] normTable;- public IDFStats(String field, float boost, Explanation idf) {+ public IDFStats(String field, float boost, Explanation idf, float[] normTable) {// TODO: Validate?this.field = field;this.idf = idf;this.boost = boost;this.queryWeight = boost * idf.getValue();+ this.normTable = normTable;}}- private Explanation explainField(int doc, Explanation freq, IDFStats stats, NumericDocValues norms) throws IOException {+ private Explanation explainField(int doc, Explanation freq, IDFStats stats, NumericDocValues norms, float[] normTable) throws IOException {Explanation tfExplanation = Explanation.match(tf(freq.getValue()), "tf(freq="+freq.getValue()+"), with freq of:", freq);float norm;- if (norms != null && norms.advanceExact(doc)) {- norm = decodeNormValue(norms.longValue());- } else {+ if (norms == null) {norm = 1f;+ } else if (norms.advanceExact(doc) == false) {+ norm = 0f;+ } else {+ norm = normTable[(int) (norms.longValue() & 0xFF)];}Explanation fieldNormExpl = Explanation.match(@@ -619,9 +667,9 @@ public abstract class TFIDFSimilarity extends Similarity {tfExplanation, stats.idf, fieldNormExpl);}- private Explanation explainScore(int doc, Explanation freq, IDFStats stats, NumericDocValues norms) throws IOException {+ private Explanation explainScore(int doc, Explanation freq, IDFStats stats, NumericDocValues norms, float[] normTable) throws IOException {Explanation queryExpl = Explanation.match(stats.boost, "boost");- Explanation fieldExpl = explainField(doc, freq, stats, norms);+ Explanation fieldExpl = explainField(doc, freq, stats, norms, normTable);if (stats.boost == 1f) {return fieldExpl;}diff --git a/lucene/core/src/java/org/apache/lucene/util/SmallFloat.java b/lucene/core/src/java/org/apache/lucene/util/SmallFloat.javaindex 39395ac5d39..317acab3b00 100644--- a/lucene/core/src/java/org/apache/lucene/util/SmallFloat.java+++ b/lucene/core/src/java/org/apache/lucene/util/SmallFloat.java@@ -97,31 +97,74 @@ public class SmallFloat {return Float.intBitsToFloat(bits);}+ /** Float-like encoding for positive longs that preserves ordering and 4 significant bits. */+ public static int longToInt4(long i) {+ if (i < 0) {+ throw new IllegalArgumentException("Only supports positive values, got " + i);+ }+ int numBits = 64 - Long.numberOfLeadingZeros(i);+ if (numBits < 4) {+ // subnormal value+ return Math.toIntExact(i);+ } else {+ // normal value+ int shift = numBits - 4;+ // only keep the 5 most significant bits+ int encoded = Math.toIntExact(i >>> shift);+ // clear the most significant bit, which is implicit+ encoded &= 0x07;+ // encode the shift, adding 1 because 0 is reserved for subnormal values+ encoded |= (shift + 1) << 3;+ return encoded;+ }+ }- /** floatToByte(b, mantissaBits=5, zeroExponent=2)- * <br>smallest nonzero value = 0.033203125- * <br>largest value = 1984.0- * <br>epsilon = 0.03125+ /**+ * Decode values encoded with {@link #longToInt4(long)}.*/- public static byte floatToByte52(float f) {- int bits = Float.floatToRawIntBits(f);- int smallfloat = bits >> (24-5);- if (smallfloat <= (63-2)<<5) {- return (bits<=0) ? (byte)0 : (byte)1;+ public static final long int4ToLong(int i) {+ long bits = i & 0x07;+ int shift = (i >>> 3) - 1;+ long decoded;+ if (shift == -1) {+ // subnormal value+ decoded = bits;+ } else {+ // normal value+ decoded = (bits | 0x08) << shift;}- if (smallfloat >= ((63-2)<<5) + 0x100) {- return -1;+ return decoded;+ }++ private static final int MAX_INT4 = longToInt4(Integer.MAX_VALUE);+ private static final int NUM_FREE_VALUES = 255 - MAX_INT4;++ /**+ * Encode an integer to a byte. It is built upon {@link #longToInt4(long)}+ * and leverages the fact that {@code longToInt4(Integer.MAX_VALUE)} is+ * less than 255 to encode low values more accurately.+ */+ public static byte intToByte4(int i) {+ if (i < 0) {+ throw new IllegalArgumentException("Only supports positive values, got " + i);+ }+ if (i < NUM_FREE_VALUES) {+ return (byte) i;+ } else {+ return (byte) (NUM_FREE_VALUES + longToInt4(i - NUM_FREE_VALUES));}- return (byte)(smallfloat - ((63-2)<<5));}- /** byteToFloat(b, mantissaBits=5, zeroExponent=2) */- public static float byte52ToFloat(byte b) {- // on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup- // is only a little bit faster (anywhere from 0% to 7%)- if (b == 0) return 0.0f;- int bits = (b&0xff) << (24-5);- bits += (63-2) << 24;- return Float.intBitsToFloat(bits);+ /**+ * Decode values that have been encoded with {@link #intToByte4(int)}.+ */+ public static int byte4ToInt(byte b) {+ int i = Byte.toUnsignedInt(b);+ if (i < NUM_FREE_VALUES) {+ return i;+ } else {+ long decoded = NUM_FREE_VALUES + int4ToLong(i - NUM_FREE_VALUES);+ return Math.toIntExact(decoded);+ }}}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.javaindex be3a2af18b7..bd483d39b6d 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexSorting.java@@ -2441,7 +2441,7 @@ public class TestIndexSorting extends LuceneTestCase {assertTrue(sparseValues.advanceExact(docID));assertTrue(sparseBinaryValues.advanceExact(docID));assertTrue(normsValues.advanceExact(docID));- assertEquals(124, normsValues.longValue());+ assertEquals(1, normsValues.longValue());assertEquals(127-docID, (int) sparseValues.longValue());assertEquals(new BytesRef(Integer.toString(127-docID)), sparseBinaryValues.binaryValue());} else {diff --git a/lucene/core/src/test/org/apache/lucene/index/TestMaxTermFrequency.java b/lucene/core/src/test/org/apache/lucene/index/TestMaxTermFrequency.javaindex 4f74c30cfe2..491660b694c 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestMaxTermFrequency.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestMaxTermFrequency.java@@ -17,6 +17,7 @@package org.apache.lucene.index;+import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;@@ -26,7 +27,9 @@ import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.analysis.MockTokenizer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;-import org.apache.lucene.search.similarities.TFIDFSimilarity;+import org.apache.lucene.search.CollectionStatistics;+import org.apache.lucene.search.TermStatistics;+import org.apache.lucene.search.similarities.Similarity;import org.apache.lucene.store.Directory;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.LuceneTestCase;@@ -35,12 +38,12 @@ import org.apache.lucene.util.TestUtil;/*** Tests the maxTermFrequency statistic in FieldInvertState*/-public class TestMaxTermFrequency extends LuceneTestCase {+public class TestMaxTermFrequency extends LuceneTestCase {Directory dir;IndexReader reader;/* expected maxTermFrequency values for our documents */ArrayList<Integer> expected = new ArrayList<>();-+@Overridepublic void setUp() throws Exception {super.setUp();@@ -59,14 +62,14 @@ public class TestMaxTermFrequency extends LuceneTestCase {reader = writer.getReader();writer.close();}-+@Overridepublic void tearDown() throws Exception {reader.close();dir.close();super.tearDown();}-+public void test() throws Exception {NumericDocValues fooNorms = MultiDocValues.getNormValues(reader, "foo");for (int i = 0; i < reader.maxDoc(); i++) {@@ -95,30 +98,42 @@ public class TestMaxTermFrequency extends LuceneTestCase {Collections.shuffle(terms, random());return Arrays.toString(terms.toArray(new String[terms.size()]));}-+/*** Simple similarity that encodes maxTermFrequency directly as a byte*/- static class TestSimilarity extends TFIDFSimilarity {+ static class TestSimilarity extends Similarity {@Override- public float lengthNorm(FieldInvertState state) {+ public long computeNorm(FieldInvertState state) {return state.getMaxTermFrequency();}@Override- public long encodeNormValue(float f) {- return (byte) f;+ public SimWeight computeWeight(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) {+ return new SimWeight() {};}@Override- public float decodeNormValue(long norm) {- return norm;+ public SimScorer simScorer(SimWeight weight, LeafReaderContext context) throws IOException {+ return new SimScorer() {++ @Override+ public float score(int doc, float freq) throws IOException {+ return 0;+ }++ @Override+ public float computeSlopFactor(int distance) {+ return 0;+ }++ @Override+ public float computePayloadFactor(int doc, int start, int end, BytesRef payload) {+ return 0;+ }+ };}- @Override public float tf(float freq) { return 0; }- @Override public float idf(long docFreq, long docCount) { return 0; }- @Override public float sloppyFreq(int distance) { return 0; }- @Override public float scorePayload(int doc, int start, int end, BytesRef payload) { return 0; }}}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestNorms.java b/lucene/core/src/test/org/apache/lucene/index/TestNorms.javaindex 64c064996be..70c7a3237e6 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestNorms.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestNorms.java@@ -32,13 +32,11 @@ import org.apache.lucene.search.TermStatistics;import org.apache.lucene.search.similarities.ClassicSimilarity;import org.apache.lucene.search.similarities.PerFieldSimilarityWrapper;import org.apache.lucene.search.similarities.Similarity;-import org.apache.lucene.search.similarities.TFIDFSimilarity;import org.apache.lucene.store.Directory;-import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.LineFileDocs;+import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.LuceneTestCase.Slow;import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;-import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.TestUtil;/**@@ -49,67 +47,6 @@ import org.apache.lucene.util.TestUtil;@Slowpublic class TestNorms extends LuceneTestCase {static final String BYTE_TEST_FIELD = "normsTestByte";-- static class CustomNormEncodingSimilarity extends TFIDFSimilarity {-- @Override- public long encodeNormValue(float f) {- return (long) f;- }-- @Override- public float decodeNormValue(long norm) {- return norm;- }-- @Override- public float lengthNorm(FieldInvertState state) {- return state.getLength();- }-- @Override public float tf(float freq) { return 0; }- @Override public float idf(long docFreq, long docCount) { return 0; }- @Override public float sloppyFreq(int distance) { return 0; }- @Override public float scorePayload(int doc, int start, int end, BytesRef payload) { return 0; }- }-- // LUCENE-1260- public void testCustomEncoder() throws Exception {- Directory dir = newDirectory();- MockAnalyzer analyzer = new MockAnalyzer(random());-- IndexWriterConfig config = newIndexWriterConfig(analyzer);- config.setSimilarity(new CustomNormEncodingSimilarity());- RandomIndexWriter writer = new RandomIndexWriter(random(), dir, config);- Document doc = new Document();- Field foo = newTextField("foo", "", Field.Store.NO);- Field bar = newTextField("bar", "", Field.Store.NO);- doc.add(foo);- doc.add(bar);-- for (int i = 0; i < 100; i++) {- bar.setStringValue("singleton");- writer.addDocument(doc);- }-- IndexReader reader = writer.getReader();- writer.close();-- NumericDocValues fooNorms = MultiDocValues.getNormValues(reader, "foo");- for (int i = 0; i < reader.maxDoc(); i++) {- assertEquals(i, fooNorms.nextDoc());- assertEquals(0, fooNorms.longValue());- }-- NumericDocValues barNorms = MultiDocValues.getNormValues(reader, "bar");- for (int i = 0; i < reader.maxDoc(); i++) {- assertEquals(i, barNorms.nextDoc());- assertEquals(1, barNorms.longValue());- }-- reader.close();- dir.close();- }public void testMaxByteNorms() throws IOException {Directory dir = newFSDirectory(createTempDir("TestNorms.testMaxByteNorms"));diff --git a/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java b/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.javaindex 0deafddc6c3..8af744f78c3 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java@@ -44,9 +44,7 @@ import org.apache.lucene.util.LuceneTestCase;public class TestOmitTf extends LuceneTestCase {public static class SimpleSimilarity extends TFIDFSimilarity {- @Override public float decodeNormValue(long norm) { return norm; }- @Override public long encodeNormValue(float f) { return (long) f; }- @Override public float lengthNorm(FieldInvertState state) { return 1; }+ @Override public float lengthNorm(int length) { return 1; }@Override public float tf(float freq) { return freq; }@Override public float sloppyFreq(int distance) { return 2.0f; }@Override public float idf(long docFreq, long docCount) { return 1.0f; }diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionMaxQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionMaxQuery.javaindex e20163ae504..112d892d59e 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionMaxQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionMaxQuery.java@@ -30,7 +30,6 @@ import org.apache.lucene.document.Field;import org.apache.lucene.document.FieldType;import org.apache.lucene.document.TextField;import org.apache.lucene.index.DirectoryReader;-import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;@@ -72,7 +71,7 @@ public class TestDisjunctionMaxQuery extends LuceneTestCase {}@Override- public float lengthNorm(FieldInvertState state) {+ public float lengthNorm(int length) {// Disable length normreturn 1;}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java b/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.javaindex fb01e1dc496..bc849e9e21f 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java@@ -33,6 +33,7 @@ import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.SortedDocValues;import org.apache.lucene.index.Term;import org.apache.lucene.search.FieldValueHitQueue.Entry;+import org.apache.lucene.search.similarities.BM25Similarity;import org.apache.lucene.search.similarities.ClassicSimilarity;import org.apache.lucene.store.Directory;import org.apache.lucene.util.BytesRef;@@ -63,7 +64,7 @@ public class TestElevationComparator extends LuceneTestCase {writer.close();IndexSearcher searcher = newSearcher(r);- searcher.setSimilarity(new ClassicSimilarity());+ searcher.setSimilarity(new BM25Similarity());runTest(searcher, true);runTest(searcher, false);@@ -98,11 +99,11 @@ public class TestElevationComparator extends LuceneTestCase {assertEquals(3, topDocs.scoreDocs[1].doc);if (reversed) {- assertEquals(2, topDocs.scoreDocs[2].doc);- assertEquals(1, topDocs.scoreDocs[3].doc);- } else {assertEquals(1, topDocs.scoreDocs[2].doc);assertEquals(2, topDocs.scoreDocs[3].doc);+ } else {+ assertEquals(2, topDocs.scoreDocs[2].doc);+ assertEquals(1, topDocs.scoreDocs[3].doc);}/*diff --git a/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.javaindex be6a87b8e63..2bbd0dd0dcb 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java@@ -37,6 +37,7 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriterConfig.OpenMode;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;+import org.apache.lucene.search.similarities.BM25Similarity;import org.apache.lucene.search.similarities.ClassicSimilarity;import org.apache.lucene.store.Directory;import org.apache.lucene.util.LuceneTestCase;@@ -309,7 +310,7 @@ public class TestPhraseQuery extends LuceneTestCase {RandomIndexWriter writer = new RandomIndexWriter(random(), directory,newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy())- .setSimilarity(new ClassicSimilarity()));+ .setSimilarity(new BM25Similarity()));Document doc = new Document();doc.add(newTextField("field", "foo firstname lastname foo", Field.Store.YES));@@ -335,9 +336,9 @@ public class TestPhraseQuery extends LuceneTestCase {// each other get a higher score:assertEquals(1.0, hits[0].score, 0.01);assertEquals(0, hits[0].doc);- assertEquals(0.62, hits[1].score, 0.01);+ assertEquals(0.63, hits[1].score, 0.01);assertEquals(1, hits[1].doc);- assertEquals(0.43, hits[2].score, 0.01);+ assertEquals(0.47, hits[2].score, 0.01);assertEquals(2, hits[2].doc);QueryUtils.check(random(), query,searcher);reader.close();diff --git a/lucene/core/src/test/org/apache/lucene/search/TestQueryRescorer.java b/lucene/core/src/test/org/apache/lucene/search/TestQueryRescorer.javaindex 8b616b5be76..ab44297c50e 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestQueryRescorer.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestQueryRescorer.java@@ -26,6 +26,7 @@ import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.NumericDocValuesField;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;@@ -49,9 +50,14 @@ public class TestQueryRescorer extends LuceneTestCase {return searcher;}+ public static IndexWriterConfig newIndexWriterConfig() {+ // We rely on more tokens = lower score:+ return LuceneTestCase.newIndexWriterConfig().setSimilarity(new ClassicSimilarity());+ }+public void testBasic() throws Exception {Directory dir = newDirectory();- RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig());Document doc = new Document();doc.add(newStringField("id", "0", Field.Store.YES));@@ -106,7 +112,7 @@ public class TestQueryRescorer extends LuceneTestCase {// Test LUCENE-5682public void testNullScorerTermQuery() throws Exception {Directory dir = newDirectory();- RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig());Document doc = new Document();doc.add(newStringField("id", "0", Field.Store.YES));@@ -145,7 +151,7 @@ public class TestQueryRescorer extends LuceneTestCase {public void testCustomCombine() throws Exception {Directory dir = newDirectory();- RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig());Document doc = new Document();doc.add(newStringField("id", "0", Field.Store.YES));@@ -196,7 +202,7 @@ public class TestQueryRescorer extends LuceneTestCase {public void testExplain() throws Exception {Directory dir = newDirectory();- RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig());Document doc = new Document();doc.add(newStringField("id", "0", Field.Store.YES));@@ -271,7 +277,7 @@ public class TestQueryRescorer extends LuceneTestCase {public void testMissingSecondPassScore() throws Exception {Directory dir = newDirectory();- RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig());Document doc = new Document();doc.add(newStringField("id", "0", Field.Store.YES));@@ -325,7 +331,7 @@ public class TestQueryRescorer extends LuceneTestCase {public void testRandom() throws Exception {Directory dir = newDirectory();int numDocs = atLeast(1000);- RandomIndexWriter w = new RandomIndexWriter(random(), dir);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig());final int[] idToNum = new int[numDocs];int maxValue = TestUtil.nextInt(random(), 10, 1000000);diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSimilarity.java b/lucene/core/src/test/org/apache/lucene/search/TestSimilarity.javaindex 3faa5c2e79d..41f88321218 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSimilarity.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSimilarity.java@@ -17,20 +17,18 @@package org.apache.lucene.search;-import org.apache.lucene.document.Field;-import org.apache.lucene.index.LeafReaderContext;-import org.apache.lucene.util.LuceneTestCase;-import java.io.IOException;-import org.apache.lucene.index.FieldInvertState;+import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;import org.apache.lucene.search.similarities.ClassicSimilarity;import org.apache.lucene.store.Directory;-import org.apache.lucene.analysis.MockAnalyzer;-import org.apache.lucene.document.Document;+import org.apache.lucene.util.LuceneTestCase;/** Similarity unit test.*@@ -39,7 +37,7 @@ import org.apache.lucene.document.Document;public class TestSimilarity extends LuceneTestCase {public static class SimpleSimilarity extends ClassicSimilarity {- @Override public float lengthNorm(FieldInvertState state) { return 1; }+ @Override public float lengthNorm(int length) { return 1; }@Override public float tf(float freq) { return freq; }@Override public float sloppyFreq(int distance) { return 2.0f; }@Override public float idf(long docFreq, long docCount) { return 1.0f; }diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSimilarityProvider.java b/lucene/core/src/test/org/apache/lucene/search/TestSimilarityProvider.javaindex fbc0b355a0d..d0b33f18390 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSimilarityProvider.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSimilarityProvider.java@@ -17,19 +17,21 @@package org.apache.lucene.search;+import java.io.IOException;+import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.index.IndexWriterConfig;+import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.MultiDocValues;import org.apache.lucene.index.NumericDocValues;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;import org.apache.lucene.search.similarities.PerFieldSimilarityWrapper;import org.apache.lucene.search.similarities.Similarity;-import org.apache.lucene.search.similarities.TFIDFSimilarity;import org.apache.lucene.store.Directory;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.LuceneTestCase;@@ -38,7 +40,7 @@ public class TestSimilarityProvider extends LuceneTestCase {private Directory directory;private DirectoryReader reader;private IndexSearcher searcher;-+@Overridepublic void setUp() throws Exception {super.setUp();@@ -51,7 +53,7 @@ public class TestSimilarityProvider extends LuceneTestCase {doc.add(field);Field field2 = newTextField("bar", "", Field.Store.NO);doc.add(field2);-+field.setStringValue("quick brown fox");field2.setStringValue("quick brown fox");iw.addDocument(doc);@@ -63,14 +65,14 @@ public class TestSimilarityProvider extends LuceneTestCase {searcher = newSearcher(reader);searcher.setSimilarity(sim);}-+@Overridepublic void tearDown() throws Exception {reader.close();directory.close();super.tearDown();}-+public void testBasics() throws Exception {// sanity check of norms writer// TODO: generalize@@ -81,7 +83,7 @@ public class TestSimilarityProvider extends LuceneTestCase {assertEquals(i, barNorms.nextDoc());assertFalse(fooNorms.longValue() == barNorms.longValue());}-+// sanity check of searchingTopDocs foodocs = searcher.search(new TermQuery(new Term("foo", "brown")), 10);assertTrue(foodocs.totalHits > 0);@@ -89,11 +91,11 @@ public class TestSimilarityProvider extends LuceneTestCase {assertTrue(bardocs.totalHits > 0);assertTrue(foodocs.scoreDocs[0].score < bardocs.scoreDocs[0].score);}-+private static class ExampleSimilarityProvider extends PerFieldSimilarityWrapper {private Similarity sim1 = new Sim1();private Similarity sim2 = new Sim2();-+@Overridepublic Similarity get(String field) {if (field.equals("foo")) {@@ -103,80 +105,73 @@ public class TestSimilarityProvider extends LuceneTestCase {}}}-- private static class Sim1 extends TFIDFSimilarity {-- @Override- public long encodeNormValue(float f) {- return (long) f;- }-- @Override- public float decodeNormValue(long norm) {- return norm;- }- @Override- public float lengthNorm(FieldInvertState state) {- return 1f;- }+ private static class Sim1 extends Similarity {@Override- public float sloppyFreq(int distance) {- return 1f;+ public long computeNorm(FieldInvertState state) {+ return 1;}@Override- public float tf(float freq) {- return 1f;+ public SimWeight computeWeight(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) {+ return new SimWeight() {};}@Override- public float idf(long docFreq, long docCount) {- return 1f;- }+ public SimScorer simScorer(SimWeight weight, LeafReaderContext context) throws IOException {+ return new SimScorer() {- @Override- public float scorePayload(int doc, int start, int end, BytesRef payload) {- return 1f;+ @Override+ public float score(int doc, float freq) throws IOException {+ return 1;+ }++ @Override+ public float computeSlopFactor(int distance) {+ return 1;+ }++ @Override+ public float computePayloadFactor(int doc, int start, int end, BytesRef payload) {+ return 1;+ }+ };}+}-- private static class Sim2 extends TFIDFSimilarity {-- @Override- public long encodeNormValue(float f) {- return (long) f;- }-- @Override- public float decodeNormValue(long norm) {- return norm;- }-- @Override- public float lengthNorm(FieldInvertState state) {- return 10f;- }- @Override- public float sloppyFreq(int distance) {- return 10f;- }+ private static class Sim2 extends Similarity {@Override- public float tf(float freq) {- return 10f;+ public long computeNorm(FieldInvertState state) {+ return 10;}@Override- public float idf(long docFreq, long docCount) {- return 10f;+ public SimWeight computeWeight(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) {+ return new SimWeight() {};}@Override- public float scorePayload(int doc, int start, int end, BytesRef payload) {- return 1f;+ public SimScorer simScorer(SimWeight weight, LeafReaderContext context) throws IOException {+ return new SimScorer() {++ @Override+ public float score(int doc, float freq) throws IOException {+ return 10;+ }++ @Override+ public float computeSlopFactor(int distance) {+ return 1;+ }++ @Override+ public float computePayloadFactor(int doc, int start, int end, BytesRef payload) {+ return 1;+ }+ };}}}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSortRescorer.java b/lucene/core/src/test/org/apache/lucene/search/TestSortRescorer.javaindex b2d435da466..6cce5fe390e 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSortRescorer.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortRescorer.java@@ -42,7 +42,7 @@ public class TestSortRescorer extends LuceneTestCase {public void setUp() throws Exception {super.setUp();dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, newIndexWriterConfig().setSimilarity(new ClassicSimilarity()));Document doc = new Document();doc.add(newStringField("id", "1", Field.Store.YES));diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestAxiomaticSimilarity.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestAxiomaticSimilarity.javaindex 44c7e1d9d16..eca6edc3e43 100644--- a/lucene/core/src/test/org/apache/lucene/search/similarities/TestAxiomaticSimilarity.java+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestAxiomaticSimilarity.java@@ -20,19 +20,6 @@ import org.apache.lucene.util.LuceneTestCase;public class TestAxiomaticSimilarity extends LuceneTestCase {- public void testSaneNormValues() {- Axiomatic sim = new AxiomaticF2EXP();- for (int i = 0; i < 256; i++) {- float len = sim.decodeNormValue((byte) i);- assertFalse("negative len: " + len + ", byte=" + i, len < 0.0f);- assertFalse("inf len: " + len + ", byte=" + i, Float.isInfinite(len));- assertFalse("nan len for byte=" + i, Float.isNaN(len));- if (i > 0) {- assertTrue("len is not decreasing: " + len + ",byte=" + i, len < sim.decodeNormValue((byte) (i - 1)));- }- }- }-public void testIllegalS() {IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new AxiomaticF2EXP(Float.POSITIVE_INFINITY, 0.1f);diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestBM25Similarity.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestBM25Similarity.javaindex dc434068258..e54ce25e87f 100644--- a/lucene/core/src/test/org/apache/lucene/search/similarities/TestBM25Similarity.java+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestBM25Similarity.java@@ -17,23 +17,27 @@package org.apache.lucene.search.similarities;+import java.io.IOException;+import java.util.stream.Collectors;+import java.util.stream.IntStream;++import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field.Store;+import org.apache.lucene.document.TextField;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.SegmentInfos;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.Explanation;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.store.Directory;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.Version;public class TestBM25Similarity extends LuceneTestCase {- public void testSaneNormValues() {- BM25Similarity sim = new BM25Similarity();- for (int i = 0; i < 256; i++) {- float len = sim.decodeNormValue((byte) i);- assertFalse("negative len: " + len + ", byte=" + i, len < 0.0f);- assertFalse("inf len: " + len + ", byte=" + i, Float.isInfinite(len));- assertFalse("nan len for byte=" + i, Float.isNaN(len));- if (i > 0) {- assertTrue("len is not decreasing: " + len + ",byte=" + i, len < sim.decodeNormValue((byte)(i-1)));- }- }- }-public void testIllegalK1() {IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new BM25Similarity(Float.POSITIVE_INFINITY, 0.75f);@@ -72,4 +76,44 @@ public class TestBM25Similarity extends LuceneTestCase {});assertTrue(expected.getMessage().contains("illegal b value"));}++ public void testLengthEncodingBackwardCompatibility() throws IOException {+ Similarity similarity = new BM25Similarity();+ for (int indexCreatedVersionMajor : new int[] { Version.LUCENE_6_0_0.major, Version.LATEST.major}) {+ for (int length : new int[] {1, 2, 4}) { // these length values are encoded accurately on both cases+ Directory dir = newDirectory();+ // set the version on the directory+ new SegmentInfos(indexCreatedVersionMajor).commit(dir);+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig().setSimilarity(similarity));+ Document doc = new Document();+ String value = IntStream.range(0, length).mapToObj(i -> "b").collect(Collectors.joining(" "));+ doc.add(new TextField("foo", value, Store.NO));+ w.addDocument(doc);+ IndexReader reader = DirectoryReader.open(w);+ IndexSearcher searcher = newSearcher(reader);+ searcher.setSimilarity(similarity);+ Explanation expl = searcher.explain(new TermQuery(new Term("foo", "b")), 0);+ Explanation docLen = findExplanation(expl, "fieldLength");+ assertNotNull(docLen);+ assertEquals(docLen.toString(), length, (int) docLen.getValue());+ w.close();+ reader.close();+ dir.close();+ }+ }+ }++ private static Explanation findExplanation(Explanation expl, String text) {+ if (expl.getDescription().equals(text)) {+ return expl;+ } else {+ for (Explanation sub : expl.getDetails()) {+ Explanation match = findExplanation(sub, text);+ if (match != null) {+ return match;+ }+ }+ }+ return null;+ }}diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestBooleanSimilarity.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestBooleanSimilarity.javaindex 23f65d30eea..c3885143547 100644--- a/lucene/core/src/test/org/apache/lucene/search/similarities/TestBooleanSimilarity.java+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestBooleanSimilarity.java@@ -34,6 +34,7 @@ import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.TestUtil;+import org.apache.lucene.util.Version;public class TestBooleanSimilarity extends LuceneTestCase {@@ -105,8 +106,8 @@ public class TestBooleanSimilarity extends LuceneTestCase {for (int iter = 0; iter < 100; ++iter) {final int length = TestUtil.nextInt(random(), 1, 100);final int position = random().nextInt(length);- final int numOverlaps = random().nextInt(50);- FieldInvertState state = new FieldInvertState("foo", position, length, numOverlaps, 100);+ final int numOverlaps = random().nextInt(length);+ FieldInvertState state = new FieldInvertState(Version.LATEST.major, "foo", position, length, numOverlaps, 100);assertEquals(sim2.computeNorm(state),sim1.computeNorm(state),diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestClassicSimilarity.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestClassicSimilarity.javaindex be07564d1d8..c7f0453d045 100644--- a/lucene/core/src/test/org/apache/lucene/search/similarities/TestClassicSimilarity.java+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestClassicSimilarity.java@@ -19,24 +19,34 @@ package org.apache.lucene.search.similarities;import java.io.IOException;import java.util.Arrays;+import java.util.stream.Collectors;+import java.util.stream.IntStream;import org.apache.lucene.document.Document;import org.apache.lucene.document.StringField;+import org.apache.lucene.document.TextField;import org.apache.lucene.document.Field.Store;import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.MultiReader;+import org.apache.lucene.index.SegmentInfos;import org.apache.lucene.index.Term;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.DisjunctionMaxQuery;+import org.apache.lucene.search.Explanation;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TopDocs;+import org.apache.lucene.search.similarities.TFIDFSimilarity.IDFStats;import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.store.Directory;import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.TestUtil;+import org.apache.lucene.util.Version;public class TestClassicSimilarity extends LuceneTestCase {private Directory directory;@@ -63,14 +73,6 @@ public class TestClassicSimilarity extends LuceneTestCase {IOUtils.close(indexReader, directory);super.tearDown();}-- // Javadocs give this as an example so we test to make sure it's correct:- public void testPrecisionLoss() throws Exception {- ClassicSimilarity sim = new ClassicSimilarity();- float v = sim.decodeNormValue(sim.encodeNormValue(.89f));- assertEquals(0.875f, v, 0.0001f);- }-public void testHit() throws IOException {Query query = new TermQuery(new Term("test", "hit"));@@ -159,16 +161,83 @@ public class TestClassicSimilarity extends LuceneTestCase {assertTrue(topDocs.scoreDocs[0].score != 0);}- public void testSaneNormValues() {+ public void testSaneNormValues() throws IOException {ClassicSimilarity sim = new ClassicSimilarity();for (int i = 0; i < 256; i++) {- float boost = sim.decodeNormValue((byte) i);+ float boost = TFIDFSimilarity.OLD_NORM_TABLE[i];+ assertFalse("negative boost: " + boost + ", byte=" + i, boost < 0.0f);+ assertFalse("inf bost: " + boost + ", byte=" + i, Float.isInfinite(boost));+ assertFalse("nan boost for byte=" + i, Float.isNaN(boost));+ if (i > 0) {+ assertTrue("boost is not increasing: " + boost + ",byte=" + i, boost > TFIDFSimilarity.OLD_NORM_TABLE[i-1]);+ }+ }++ TFIDFSimilarity.IDFStats stats = (IDFStats) sim.computeWeight(1f, new IndexSearcher(new MultiReader()).collectionStatistics("foo"));+ for (int i = 0; i < 256; i++) {+ float boost = stats.normTable[i];assertFalse("negative boost: " + boost + ", byte=" + i, boost < 0.0f);assertFalse("inf bost: " + boost + ", byte=" + i, Float.isInfinite(boost));assertFalse("nan boost for byte=" + i, Float.isNaN(boost));if (i > 0) {- assertTrue("boost is not increasing: " + boost + ",byte=" + i, boost > sim.decodeNormValue((byte)(i-1)));+ assertTrue("boost is not decreasing: " + boost + ",byte=" + i, boost < stats.normTable[i-1]);}}}++ public void testNormEncodingBackwardCompatibility() throws IOException {+ Similarity similarity = new ClassicSimilarity();+ for (int indexCreatedVersionMajor : new int[] { Version.LUCENE_6_0_0.major, Version.LATEST.major}) {+ for (int length : new int[] {1, 4, 16 }) { // these length values are encoded accurately on both cases+ Directory dir = newDirectory();+ // set the version on the directory+ new SegmentInfos(indexCreatedVersionMajor).commit(dir);+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig().setSimilarity(similarity));+ Document doc = new Document();+ String value = IntStream.range(0, length).mapToObj(i -> "b").collect(Collectors.joining(" "));+ doc.add(new TextField("foo", value, Store.NO));+ w.addDocument(doc);+ IndexReader reader = DirectoryReader.open(w);+ IndexSearcher searcher = newSearcher(reader);+ searcher.setSimilarity(similarity);+ Explanation expl = searcher.explain(new TermQuery(new Term("foo", "b")), 0);+ Explanation fieldNorm = findExplanation(expl, "fieldNorm");+ assertNotNull(fieldNorm);+ assertEquals(fieldNorm.toString(), 1/Math.sqrt(length), fieldNorm.getValue(), 0f);+ w.close();+ reader.close();+ dir.close();+ }+ }+ }++ private static Explanation findExplanation(Explanation expl, String text) {+ if (expl.getDescription().startsWith(text)) {+ return expl;+ } else {+ for (Explanation sub : expl.getDetails()) {+ Explanation match = findExplanation(sub, text);+ if (match != null) {+ return match;+ }+ }+ }+ return null;+ }++ public void testSameNormsAsBM25() {+ ClassicSimilarity sim1 = new ClassicSimilarity();+ BM25Similarity sim2 = new BM25Similarity();+ sim2.setDiscountOverlaps(true);+ for (int iter = 0; iter < 100; ++iter) {+ final int length = TestUtil.nextInt(random(), 1, 1000);+ final int position = random().nextInt(length);+ final int numOverlaps = random().nextInt(length);+ FieldInvertState state = new FieldInvertState(Version.LATEST.major, "foo", position, length, numOverlaps, 100);+ assertEquals(+ sim2.computeNorm(state),+ sim1.computeNorm(state),+ 0f);+ }+ }}diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.javaindex 373b9e61257..59be73ac355 100644--- a/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java@@ -20,16 +20,23 @@ package org.apache.lucene.search.similarities;import java.io.IOException;import java.util.ArrayList;import java.util.List;+import java.util.stream.Collectors;+import java.util.stream.IntStream;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.FieldType;import org.apache.lucene.document.TextField;+import org.apache.lucene.document.Field.Store;+import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.index.IndexOptions;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.SegmentInfos;import org.apache.lucene.index.Term;+import org.apache.lucene.index.TermContext;import org.apache.lucene.search.CollectionStatistics;import org.apache.lucene.search.Explanation;import org.apache.lucene.search.IndexSearcher;@@ -37,9 +44,13 @@ import org.apache.lucene.search.Query;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TermStatistics;import org.apache.lucene.search.TopDocs;+import org.apache.lucene.search.similarities.Similarity.SimWeight;import org.apache.lucene.store.Directory;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.Version;++import com.carrotsearch.randomizedtesting.generators.RandomPicks;/*** Tests the {@link SimilarityBase}-based Similarities. Contains unit tests and@@ -586,11 +597,11 @@ public class TestSimilarityBase extends LuceneTestCase {// LUCENE-5221public void testDiscountOverlapsBoost() throws IOException {- ClassicSimilarity expected = new ClassicSimilarity();+ BM25Similarity expected = new BM25Similarity();SimilarityBase actual = new DFRSimilarity(new BasicModelIne(), new AfterEffectB(), new NormalizationH2());expected.setDiscountOverlaps(false);actual.setDiscountOverlaps(false);- FieldInvertState state = new FieldInvertState("foo");+ FieldInvertState state = new FieldInvertState(Version.LATEST.major, "foo");state.setLength(5);state.setNumOverlap(2);assertEquals(expected.computeNorm(state), actual.computeNorm(state));@@ -598,64 +609,32 @@ public class TestSimilarityBase extends LuceneTestCase {actual.setDiscountOverlaps(true);assertEquals(expected.computeNorm(state), actual.computeNorm(state));}-- public void testSaneNormValues() {- for (SimilarityBase sim : sims) {- for (int i = 0; i < 256; i++) {- float len = sim.decodeNormValue((byte) i);- assertFalse("negative len: " + len + ", byte=" + i + ", sim=" + sim, len < 0.0f);- assertFalse("inf len: " + len + ", byte=" + i + ", sim=" + sim, Float.isInfinite(len));- assertFalse("nan len for byte=" + i + ", sim=" + sim, Float.isNaN(len));- if (i > 0) {- assertTrue("len is not decreasing: " + len + ",byte=" + i + ",sim=" + sim, len < sim.decodeNormValue((byte)(i-1)));- }- }- }- }-- /**- * make sure the similarity does not go crazy when tested against all possible norm values.- */- public void testCrazyIndexTimeBoosts() throws Exception {- long avgLength = 750;- long docCount = 500000;- long numTokens = docCount * avgLength;-- CollectionStatistics collectionStats = new CollectionStatistics("body", docCount, docCount, numTokens, numTokens);-- long docFreq = 2000;- long totalTermFreq = 2000 * avgLength;-- TermStatistics termStats = new TermStatistics(new BytesRef("term"), docFreq, totalTermFreq);-- for (SimilarityBase sim : sims) {- if (sim instanceof IBSimilarity) {- if (((IBSimilarity)sim).getDistribution() instanceof DistributionSPL) {- // score goes infinite for tiny doc lengths and negative for huge doc lengths- // TODO: fix this- continue;- }- } else if (sim instanceof DFRSimilarity) {- BasicModel model = ((DFRSimilarity)sim).getBasicModel();- if (model instanceof BasicModelD || model instanceof BasicModelP) {- // score goes NaN for tiny doc lengths- // TODO: fix this- continue;- } else if (model instanceof BasicModelBE) {- // score goes negative infinity for tiny doc lengths- // TODO: fix this- continue;- }- }- BasicStats stats = (BasicStats) sim.computeWeight(1f, collectionStats, termStats);- for (float tf = 1.0f; tf <= 10.0f; tf += 1.0f) {- for (int i = 0; i < 256; i++) {- float len = sim.decodeNormValue((byte) i);- float score = sim.score(stats, tf, len);- assertFalse("negative score for " + sim + ", len=" + len + ",score=" + score, score < 0.0f);- assertFalse("inf score for " + sim + ", len=" + len, Float.isInfinite(score));- assertFalse("nan score for " + sim + ", len=" + len, Float.isNaN(score));- }++ public void testLengthEncodingBackwardCompatibility() throws IOException {+ Similarity similarity = RandomPicks.randomFrom(random(), sims);+ for (int indexCreatedVersionMajor : new int[] { Version.LUCENE_6_0_0.major, Version.LATEST.major}) {+ for (int length : new int[] {1, 2, 4}) { // these length values are encoded accurately on both cases+ Directory dir = newDirectory();+ // set the version on the directory+ new SegmentInfos(indexCreatedVersionMajor).commit(dir);+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig().setSimilarity(similarity));+ Document doc = new Document();+ String value = IntStream.range(0, length).mapToObj(i -> "b").collect(Collectors.joining(" "));+ doc.add(new TextField("foo", value, Store.NO));+ w.addDocument(doc);+ IndexReader reader = DirectoryReader.open(w);+ IndexSearcher searcher = newSearcher(reader);+ searcher.setSimilarity(similarity);+ Term term = new Term("foo", "b");+ TermContext context = TermContext.build(reader.getContext(), term);+ SimWeight simWeight = similarity.computeWeight(1f, searcher.collectionStatistics("foo"), searcher.termStatistics(term, context));+ SimilarityBase.BasicSimScorer simScorer = (SimilarityBase.BasicSimScorer) similarity.simScorer(simWeight, reader.leaves().get(0));+ float docLength = simScorer.getLengthValue(0);+ assertEquals(length, (int) docLength);++ w.close();+ reader.close();+ dir.close();}}}diff --git a/lucene/core/src/test/org/apache/lucene/util/TestSmallFloat.java b/lucene/core/src/test/org/apache/lucene/util/TestSmallFloat.javaindex 86c6bb812b0..dca5f2d6b23 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestSmallFloat.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestSmallFloat.java@@ -16,6 +16,8 @@*/package org.apache.lucene.util;+import java.util.Arrays;+public class TestSmallFloat extends LuceneTestCase {// original lucene byteToFloat@@ -87,10 +89,6 @@ public class TestSmallFloat extends LuceneTestCase {float f3 = SmallFloat.byte315ToFloat((byte)i);assertEquals(f1,f2,0.0);assertEquals(f2,f3,0.0);-- float f4 = SmallFloat.byteToFloat((byte)i,5,2);- float f5 = SmallFloat.byte52ToFloat((byte)i);- assertEquals(f4,f5,0.0);}}@@ -121,10 +119,51 @@ public class TestSmallFloat extends LuceneTestCase {byte b3 = SmallFloat.floatToByte315(f);assertEquals(b1,b2);assertEquals(b2,b3);+ }+ }++ public void testInt4() {+ for (int i = 0; i <= 16; ++i) {+ // all values in 0-16 are encoded accurately+ assertEquals(i, SmallFloat.int4ToLong(SmallFloat.longToInt4(i)));+ }+ final int maxEncoded = SmallFloat.longToInt4(Long.MAX_VALUE);+ for (int i = 1; i < maxEncoded; ++i) {+ assertTrue(SmallFloat.int4ToLong(i) > SmallFloat.int4ToLong(i - 1));+ }+ final int iters = atLeast(1000);+ for (int iter = 0; iter < iters; ++iter) {+ final long l = TestUtil.nextLong(random(), 0, 1L << TestUtil.nextInt(random(), 5, 61));+ int numBits = 64 - Long.numberOfLeadingZeros(l);+ long expected = l;+ if (numBits > 4) {+ long mask = ~0L << (numBits - 4);+ expected &= mask;+ }+ long l2 = SmallFloat.int4ToLong(SmallFloat.longToInt4(l));+ assertEquals(expected, l2);+ }+ }- byte b4 = SmallFloat.floatToByte(f,5,2);- byte b5 = SmallFloat.floatToByte52(f);- assertEquals(b4,b5);+ public void testByte4() {+ int[] decoded = new int[256];+ for (int b = 0; b < 256; ++b) {+ decoded[b] = SmallFloat.byte4ToInt((byte) b);+ assertEquals((byte) b, SmallFloat.intToByte4(decoded[b]));+ }+ for (int i = 1; i < 256; ++i) {+ assertTrue(decoded[i] > decoded[i-1]);+ }+ assertEquals((byte) 255, SmallFloat.intToByte4(Integer.MAX_VALUE));+ final int iters = atLeast(1000);+ for (int iter = 0; iter < iters; ++iter) {+ final int i = random().nextInt(1 << TestUtil.nextInt(random(), 5, 30));+ int idx = Arrays.binarySearch(decoded, i);+ if (idx < 0) {+ idx = -2 - idx;+ }+ assertTrue(decoded[idx] <= i);+ assertEquals((byte) idx, SmallFloat.intToByte4(i));}}@@ -146,5 +185,4 @@ public class TestSmallFloat extends LuceneTestCase {}}***/-}diff --git a/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionRescorer.java b/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionRescorer.javaindex 98012a5e8b2..20a6ebab664 100644--- a/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionRescorer.java+++ b/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionRescorer.java@@ -44,7 +44,7 @@ public class TestExpressionRescorer extends LuceneTestCase {public void setUp() throws Exception {super.setUp();dir = newDirectory();- RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, newIndexWriterConfig().setSimilarity(new ClassicSimilarity()));Document doc = new Document();doc.add(newStringField("id", "1", Field.Store.YES));diff --git a/lucene/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.java b/lucene/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.javaindex c37709b5eea..d03432e8d42 100644--- a/lucene/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.java+++ b/lucene/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.java@@ -72,6 +72,8 @@ import org.apache.lucene.search.PhraseQuery.Builder;import org.apache.lucene.search.PrefixQuery;import org.apache.lucene.search.Query;import org.apache.lucene.search.RegexpQuery;+import org.apache.lucene.search.Sort;+import org.apache.lucene.search.SortField;import org.apache.lucene.search.SynonymQuery;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TermRangeQuery;@@ -147,7 +149,7 @@ public class HighlighterTest extends BaseTokenStreamTestCase implements FormatteCustomScoreQuery query = new CustomScoreQuery(termQuery);searcher = newSearcher(reader);- TopDocs hits = searcher.search(query, 10);+ TopDocs hits = searcher.search(query, 10, new Sort(SortField.FIELD_DOC, SortField.FIELD_SCORE));assertEquals(2, hits.totalHits);QueryScorer scorer = new QueryScorer(query, FIELD_NAME);Highlighter highlighter = new Highlighter(scorer);@@ -199,7 +201,7 @@ public class HighlighterTest extends BaseTokenStreamTestCase implements Formattequery.add(new Term(FIELD_NAME, "very"));searcher = newSearcher(reader);- TopDocs hits = searcher.search(query, 10);+ TopDocs hits = searcher.search(query, 10, new Sort(SortField.FIELD_DOC, SortField.FIELD_SCORE));assertEquals(2, hits.totalHits);QueryScorer scorer = new QueryScorer(query, FIELD_NAME);Highlighter highlighter = new Highlighter(scorer);@@ -271,7 +273,7 @@ public class HighlighterTest extends BaseTokenStreamTestCase implements Formatte};searcher = newSearcher(reader);- TopDocs hits = searcher.search(query, 10);+ TopDocs hits = searcher.search(query, 10, new Sort(SortField.FIELD_DOC, SortField.FIELD_SCORE));assertEquals(2, hits.totalHits);QueryScorer scorer = new QueryScorer(query, FIELD_NAME);Highlighter highlighter = new Highlighter(scorer);diff --git a/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java b/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.javaindex a1f2b0789ee..a409a17c631 100644--- a/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java+++ b/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java@@ -892,7 +892,7 @@ public class MemoryIndex {NumericDocValues getNormDocValues() {if (norm == null) {- FieldInvertState invertState = new FieldInvertState(fieldInfo.name, fieldInfo.number,+ FieldInvertState invertState = new FieldInvertState(Version.LATEST.major, fieldInfo.name, fieldInfo.number,numTokens, numOverlapTokens, 0);final long value = normSimilarity.computeNorm(invertState);if (DEBUG) System.err.println("MemoryIndexReader.norms: " + fieldInfo.name + ":" + value + ":" + numTokens);diff --git a/lucene/memory/src/test/org/apache/lucene/index/memory/TestMemoryIndex.java b/lucene/memory/src/test/org/apache/lucene/index/memory/TestMemoryIndex.javaindex 1e20f30509b..3d3a12c97ce 100644--- a/lucene/memory/src/test/org/apache/lucene/index/memory/TestMemoryIndex.java+++ b/lucene/memory/src/test/org/apache/lucene/index/memory/TestMemoryIndex.java@@ -50,6 +50,7 @@ import org.apache.lucene.index.IndexOptions;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexableField;import org.apache.lucene.index.LeafReader;+import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.NumericDocValues;import org.apache.lucene.index.PostingsEnum;import org.apache.lucene.index.SortedDocValues;@@ -57,13 +58,16 @@ import org.apache.lucene.index.SortedNumericDocValues;import org.apache.lucene.index.SortedSetDocValues;import org.apache.lucene.index.Term;import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.search.CollectionStatistics;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.PhraseQuery;import org.apache.lucene.search.Query;import org.apache.lucene.search.TermQuery;+import org.apache.lucene.search.TermStatistics;import org.apache.lucene.search.similarities.BM25Similarity;import org.apache.lucene.search.similarities.ClassicSimilarity;+import org.apache.lucene.search.similarities.Similarity;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.TestUtil;@@ -145,32 +149,32 @@ public class TestMemoryIndex extends LuceneTestCase {assertEquals(reader.getTermVectors(0).size(), 1);}-+public void testReaderConsistency() throws IOException {Analyzer analyzer = new MockPayloadAnalyzer();-+// defaultsMemoryIndex mi = new MemoryIndex();mi.addField("field", "some terms be here", analyzer);TestUtil.checkReader(mi.createSearcher().getIndexReader());-+// all combinations of offsets/payloads optionsmi = new MemoryIndex(true, true);mi.addField("field", "some terms be here", analyzer);TestUtil.checkReader(mi.createSearcher().getIndexReader());-+mi = new MemoryIndex(true, false);mi.addField("field", "some terms be here", analyzer);TestUtil.checkReader(mi.createSearcher().getIndexReader());-+mi = new MemoryIndex(false, true);mi.addField("field", "some terms be here", analyzer);TestUtil.checkReader(mi.createSearcher().getIndexReader());-+mi = new MemoryIndex(false, false);mi.addField("field", "some terms be here", analyzer);TestUtil.checkReader(mi.createSearcher().getIndexReader());-+analyzer.close();}@@ -187,11 +191,23 @@ public class TestMemoryIndex extends LuceneTestCase {float n1 = norms.longValue();// Norms are re-computed when we change the Similarity- mi.setSimilarity(new ClassicSimilarity() {+ mi.setSimilarity(new Similarity() {+@Override- public float lengthNorm(FieldInvertState state) {+ public long computeNorm(FieldInvertState state) {return 74;}++ @Override+ public SimWeight computeWeight(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) {+ throw new UnsupportedOperationException();+ }++ @Override+ public SimScorer simScorer(SimWeight weight, LeafReaderContext context) throws IOException {+ throw new UnsupportedOperationException();+ }+});norms = reader.getNormValues("f1");assertEquals(0, norms.nextDoc());diff --git a/lucene/misc/src/java/org/apache/lucene/misc/SweetSpotSimilarity.java b/lucene/misc/src/java/org/apache/lucene/misc/SweetSpotSimilarity.javaindex 9307b944f70..8cc962df292 100644--- a/lucene/misc/src/java/org/apache/lucene/misc/SweetSpotSimilarity.java+++ b/lucene/misc/src/java/org/apache/lucene/misc/SweetSpotSimilarity.java@@ -17,7 +17,6 @@package org.apache.lucene.misc;import org.apache.lucene.search.similarities.ClassicSimilarity;-import org.apache.lucene.index.FieldInvertState;/*** <p>@@ -86,7 +85,7 @@ public class SweetSpotSimilarity extends ClassicSimilarity {* Sets the default function variables used by lengthNorm when no field* specific variables have been set.*- * @see #computeLengthNorm+ * @see #lengthNorm*/public void setLengthNormFactors(int min, int max, float steepness, boolean discountOverlaps) {this.ln_min = min;@@ -94,25 +93,6 @@ public class SweetSpotSimilarity extends ClassicSimilarity {this.ln_steep = steepness;this.discountOverlaps = discountOverlaps;}-- /**- * Implemented as <code> state.getBoost() *- * computeLengthNorm(numTokens) </code> where- * numTokens does not count overlap tokens if- * discountOverlaps is true by default or true for this- * specific field.- */- @Override- public float lengthNorm(FieldInvertState state) {- final int numTokens;-- if (discountOverlaps)- numTokens = state.getLength() - state.getNumOverlap();- else- numTokens = state.getLength();-- return computeLengthNorm(numTokens);- }/*** Implemented as:@@ -133,7 +113,8 @@ public class SweetSpotSimilarity extends ClassicSimilarity {* @see #setLengthNormFactors* @see <a href="doc-files/ss.computeLengthNorm.svg">An SVG visualization of this function</a>*/- public float computeLengthNorm(int numTerms) {+ @Override+ public float lengthNorm(int numTerms) {final int l = ln_min;final int h = ln_max;final float s = ln_steep;diff --git a/lucene/misc/src/test/org/apache/lucene/misc/SweetSpotSimilarityTest.java b/lucene/misc/src/test/org/apache/lucene/misc/SweetSpotSimilarityTest.javaindex cd6a819bdc9..d21a3eac0a8 100644--- a/lucene/misc/src/test/org/apache/lucene/misc/SweetSpotSimilarityTest.java+++ b/lucene/misc/src/test/org/apache/lucene/misc/SweetSpotSimilarityTest.java@@ -16,27 +16,62 @@*/package org.apache.lucene.misc;+import java.io.IOException;+import java.util.Collections;+import java.util.stream.Collectors;+import java.util.stream.IntStream;++import org.apache.lucene.document.Field.Store;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.Explanation;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.similarities.ClassicSimilarity;import org.apache.lucene.search.similarities.PerFieldSimilarityWrapper;import org.apache.lucene.search.similarities.Similarity;import org.apache.lucene.search.similarities.TFIDFSimilarity;+import org.apache.lucene.store.Directory;import org.apache.lucene.util.LuceneTestCase;-import org.apache.lucene.index.FieldInvertState;/*** Test of the SweetSpotSimilarity*/public class SweetSpotSimilarityTest extends LuceneTestCase {- public static float computeAndDecodeNorm(SweetSpotSimilarity decode, Similarity encode, FieldInvertState state) {- return decode.decodeNormValue(computeAndGetNorm(encode, state));+ private static float computeNorm(Similarity sim, String field, int length) throws IOException {+ String value = IntStream.range(0, length).mapToObj(i -> "a").collect(Collectors.joining(" "));+ Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig().setSimilarity(sim));+ w.addDocument(Collections.singleton(newTextField(field, value, Store.NO)));+ DirectoryReader reader = DirectoryReader.open(w);+ w.close();+ IndexSearcher searcher = new IndexSearcher(reader);+ searcher.setSimilarity(sim);+ Explanation expl = searcher.explain(new TermQuery(new Term(field, "a")), 0);+ reader.close();+ dir.close();+ Explanation norm = findExplanation(expl, "fieldNorm");+ assertNotNull(norm);+ return norm.getValue();}-- public static byte computeAndGetNorm(Similarity s, FieldInvertState state) {- return (byte) s.computeNorm(state);++ private static Explanation findExplanation(Explanation expl, String text) {+ if (expl.getDescription().startsWith(text)) {+ return expl;+ } else {+ for (Explanation sub : expl.getDetails()) {+ Explanation match = findExplanation(sub, text);+ if (match != null) {+ return match;+ }+ }+ }+ return null;}- public void testSweetSpotComputeNorm() {+ public void testSweetSpotComputeNorm() throws IOException {final SweetSpotSimilarity ss = new SweetSpotSimilarity();ss.setLengthNormFactors(1,1,0.5f,true);@@ -46,12 +81,10 @@ public class SweetSpotSimilarityTest extends LuceneTestCase {// base case, should degrade- FieldInvertState invertState = new FieldInvertState("bogus");for (int i = 1; i < 1000; i++) {- invertState.setLength(i);assertEquals("base case: i="+i,- computeAndGetNorm(d, invertState),- computeAndGetNorm(s, invertState),+ computeNorm(d, "bogus", i),+ computeNorm(s, "bogus", i),0.0f);}@@ -60,22 +93,19 @@ public class SweetSpotSimilarityTest extends LuceneTestCase {ss.setLengthNormFactors(3,10,0.5f,true);for (int i = 3; i <=10; i++) {- invertState.setLength(i);assertEquals("3,10: spot i="+i,1.0f,- computeAndDecodeNorm(ss, ss, invertState),+ computeNorm(ss, "bogus", i),0.0f);}for (int i = 10; i < 1000; i++) {- invertState.setLength(i-9);- final byte normD = computeAndGetNorm(d, invertState);- invertState.setLength(i);- final byte normS = computeAndGetNorm(s, invertState);+ final float normD = computeNorm(d, "bogus", i - 9);+ final float normS = computeNorm(s, "bogus", i);assertEquals("3,10: 10<x : i="+i,normD,normS,- 0.0f);+ 0.01f);}@@ -106,78 +136,60 @@ public class SweetSpotSimilarityTest extends LuceneTestCase {}};- invertState = new FieldInvertState("foo");for (int i = 3; i <=10; i++) {- invertState.setLength(i);assertEquals("f: 3,10: spot i="+i,1.0f,- computeAndDecodeNorm(ss, sp, invertState),+ computeNorm(sp, "foo", i),0.0f);}for (int i = 10; i < 1000; i++) {- invertState.setLength(i-9);- final byte normD = computeAndGetNorm(d, invertState);- invertState.setLength(i);- final byte normS = computeAndGetNorm(sp, invertState);+ final float normD = computeNorm(d, "foo", i-9);+ final float normS = computeNorm(sp, "foo", i);assertEquals("f: 3,10: 10<x : i="+i,normD,normS,- 0.0f);+ 0.01f);}- invertState = new FieldInvertState("bar");for (int i = 8; i <=13; i++) {- invertState.setLength(i);assertEquals("f: 8,13: spot i="+i,1.0f,- computeAndDecodeNorm(ss, sp, invertState),- 0.0f);+ computeNorm(sp, "bar", i),+ 0.01f);}- invertState = new FieldInvertState("yak");for (int i = 6; i <=9; i++) {- invertState.setLength(i);assertEquals("f: 6,9: spot i="+i,1.0f,- computeAndDecodeNorm(ss, sp, invertState),- 0.0f);+ computeNorm(sp, "yak", i),+ 0.01f);}- invertState = new FieldInvertState("bar");for (int i = 13; i < 1000; i++) {- invertState.setLength(i-12);- final byte normD = computeAndGetNorm(d, invertState);- invertState.setLength(i);- final byte normS = computeAndGetNorm(sp, invertState);+ final float normD = computeNorm(d, "bar", i-12);+ final float normS = computeNorm(sp, "bar", i);assertEquals("f: 8,13: 13<x : i="+i,normD,normS,- 0.0f);+ 0.01f);}- invertState = new FieldInvertState("yak");for (int i = 9; i < 1000; i++) {- invertState.setLength(i-8);- final byte normD = computeAndGetNorm(d, invertState);- invertState.setLength(i);- final byte normS = computeAndGetNorm(sp, invertState);+ final float normD = computeNorm(d, "yak", i-8);+ final float normS = computeNorm(sp, "yak", i);assertEquals("f: 6,9: 9<x : i="+i,normD,normS,- 0.0f);+ 0.01f);}// steepnessfor (int i = 9; i < 1000; i++) {- invertState = new FieldInvertState("a");- invertState.setLength(i);- final byte normSS = computeAndGetNorm(sp, invertState);- invertState = new FieldInvertState("b");- invertState.setLength(i);- final byte normS = computeAndGetNorm(sp, invertState);+ final float normSS = computeNorm(sp, "a", i);+ final float normS = computeNorm(sp, "b", i);assertTrue("s: i="+i+" : a="+normSS+" < b="+normS,normSS < normS);diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/NormValueSource.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/NormValueSource.javaindex d55645411f7..ea63de9345e 100644--- a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/NormValueSource.java+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/NormValueSource.java@@ -20,19 +20,24 @@ import java.io.IOException;import java.util.Map;import org.apache.lucene.index.LeafReaderContext;-import org.apache.lucene.index.NumericDocValues;import org.apache.lucene.queries.function.FunctionValues;import org.apache.lucene.queries.function.ValueSource;import org.apache.lucene.queries.function.docvalues.FloatDocValues;+import org.apache.lucene.search.CollectionStatistics;import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.TermStatistics;import org.apache.lucene.search.similarities.TFIDFSimilarity;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.search.similarities.Similarity.SimScorer;+import org.apache.lucene.search.similarities.Similarity.SimWeight;/**- * Function that returns {@link TFIDFSimilarity#decodeNormValue(long)}- * for every document.+ * Function that returns the decoded norm for every document.* <p>* Note that the configured Similarity for the field must be- * a subclass of {@link TFIDFSimilarity}+ * a subclass of {@link TFIDFSimilarity} and the contribution of+ * the TF needs to be 1 when the freq is 1 and the contribution+ * of the IDF needs to be 1 when docFreq == docCount == 1.* @lucene.internal */public class NormValueSource extends ValueSource {protected final String field;@@ -61,11 +66,12 @@ public class NormValueSource extends ValueSource {if (similarity == null) {throw new UnsupportedOperationException("requires a TFIDFSimilarity (such as ClassicSimilarity)");}- final NumericDocValues norms = readerContext.reader().getNormValues(field);-- if (norms == null) {- return new ConstDoubleDocValues(0.0, this);- }+ // Only works if the contribution of the tf is 1 when the freq is 1 and contribution of the idf+ // is 1 when docCount == docFreq == 1+ final SimWeight simWeight = similarity.computeWeight(1f,+ new CollectionStatistics(field, 1, 1, 1, 1),+ new TermStatistics(new BytesRef("bogus"), 1, 1));+ final SimScorer simScorer = similarity.simScorer(simWeight, readerContext);return new FloatDocValues(this) {int lastDocID = -1;@@ -74,16 +80,8 @@ public class NormValueSource extends ValueSource {if (docID < lastDocID) {throw new AssertionError("docs out of order: lastDocID=" + lastDocID + " docID=" + docID);}- if (docID > norms.docID()) {- norms.advance(docID);- }- long norm;- if (docID == norms.docID()) {- norm = norms.longValue();- } else {- norm = 0;- }- return similarity.decodeNormValue(norm);+ lastDocID = docID;+ return simScorer.score(docID, 1f);}};}diff --git a/lucene/queries/src/test/org/apache/lucene/queries/function/TestLongNormValueSource.java b/lucene/queries/src/test/org/apache/lucene/queries/function/TestLongNormValueSource.javaindex 11060e5737c..842c117e8ad 100644--- a/lucene/queries/src/test/org/apache/lucene/queries/function/TestLongNormValueSource.java+++ b/lucene/queries/src/test/org/apache/lucene/queries/function/TestLongNormValueSource.java@@ -21,7 +21,6 @@ import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.TextField;-import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.RandomIndexWriter;@@ -33,10 +32,9 @@ import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.Sort;import org.apache.lucene.search.SortField;import org.apache.lucene.search.TopDocs;+import org.apache.lucene.search.similarities.ClassicSimilarity;import org.apache.lucene.search.similarities.Similarity;-import org.apache.lucene.search.similarities.TFIDFSimilarity;import org.apache.lucene.store.Directory;-import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.LuceneTestCase;import org.junit.AfterClass;import org.junit.BeforeClass;@@ -48,7 +46,7 @@ public class TestLongNormValueSource extends LuceneTestCase {static IndexSearcher searcher;static Analyzer analyzer;- private static Similarity sim = new PreciseClassicSimilarity();+ private static Similarity sim = new ClassicSimilarity();@BeforeClasspublic static void beforeClass() throws Exception {@@ -116,114 +114,3 @@ public class TestLongNormValueSource extends LuceneTestCase {CheckHits.checkExplanations(q, "", searcher);}}---/** Encodes norm as 4-byte float. */-class PreciseClassicSimilarity extends TFIDFSimilarity {-- /** Sole constructor: parameter-free */- public PreciseClassicSimilarity() {}-- /**- * Encodes a normalization factor for storage in an index.- * <p>- * The encoding uses a three-bit mantissa, a five-bit exponent, and the- * zero-exponent point at 15, thus representing values from around 7x10^9 to- * 2x10^-9 with about one significant decimal digit of accuracy. Zero is also- * represented. Negative numbers are rounded up to zero. Values too large to- * represent are rounded down to the largest representable value. Positive- * values too small to represent are rounded up to the smallest positive- * representable value.- *- * @see org.apache.lucene.util.SmallFloat- */- @Override- public final long encodeNormValue(float f) {- return Float.floatToIntBits(f);- }-- /**- * Decodes the norm value, assuming it is a single byte.- *- * @see #encodeNormValue(float)- */- @Override- public final float decodeNormValue(long norm) {- return Float.intBitsToFloat((int)norm);- }-- /** Implemented as- * <code>state.getBoost()*lengthNorm(numTerms)</code>, where- * <code>numTerms</code> is {@link org.apache.lucene.index.FieldInvertState#getLength()} if {@link- * #setDiscountOverlaps} is false, else it's {@link- * org.apache.lucene.index.FieldInvertState#getLength()} - {@link- * org.apache.lucene.index.FieldInvertState#getNumOverlap()}.- *- * @lucene.experimental */- @Override- public float lengthNorm(FieldInvertState state) {- final int numTerms;- if (discountOverlaps) {- numTerms = state.getLength() - state.getNumOverlap();- } else {- numTerms = state.getLength();- }- return (float) (1.0 / Math.sqrt(numTerms));- }-- /** Implemented as <code>sqrt(freq)</code>. */- @Override- public float tf(float freq) {- return (float)Math.sqrt(freq);- }-- /** Implemented as <code>1 / (distance + 1)</code>. */- @Override- public float sloppyFreq(int distance) {- return 1.0f / (distance + 1);- }-- /** The default implementation returns <code>1</code> */- @Override- public float scorePayload(int doc, int start, int end, BytesRef payload) {- return 1;- }-- /** Implemented as <code>log(docCount/(docFreq+1)) + 1</code>. */- @Override- public float idf(long docFreq, long docCount) {- return (float)(Math.log(docCount/(double)(docFreq+1)) + 1.0);- }-- /**- * True if overlap tokens (tokens with a position of increment of zero) are- * discounted from the document's length.- */- protected boolean discountOverlaps = true;-- /** Determines whether overlap tokens (Tokens with- * 0 position increment) are ignored when computing- * norm. By default this is true, meaning overlap- * tokens do not count when computing norms.- *- * @lucene.experimental- *- * @see #computeNorm- */- public void setDiscountOverlaps(boolean v) {- discountOverlaps = v;- }-- /**- * Returns true if overlap tokens are discounted from the document's length.- * @see #setDiscountOverlaps- */- public boolean getDiscountOverlaps() {- return discountOverlaps;- }-- @Override- public String toString() {- return "DefaultSimilarity";- }-}diff --git a/lucene/queries/src/test/org/apache/lucene/queries/function/TestValueSources.java b/lucene/queries/src/test/org/apache/lucene/queries/function/TestValueSources.javaindex 800859036eb..4822e0304a6 100644--- a/lucene/queries/src/test/org/apache/lucene/queries/function/TestValueSources.java+++ b/lucene/queries/src/test/org/apache/lucene/queries/function/TestValueSources.java@@ -367,7 +367,7 @@ public class TestValueSources extends LuceneTestCase {// no norm field (so agnostic to indexed similarity)searcher.setSimilarity(new ClassicSimilarity());ValueSource vs = new NormValueSource("byte");- assertHits(new FunctionQuery(vs), new float[] { 0f, 0f });+ assertHits(new FunctionQuery(vs), new float[] { 1f, 1f });// regardless of whether norms exist, value source exists == 0assertAllExist(vs);diff --git a/lucene/queries/src/test/org/apache/lucene/queries/payloads/TestPayloadScoreQuery.java b/lucene/queries/src/test/org/apache/lucene/queries/payloads/TestPayloadScoreQuery.javaindex 810e4c0a30e..f00cc9b4763 100644--- a/lucene/queries/src/test/org/apache/lucene/queries/payloads/TestPayloadScoreQuery.java+++ b/lucene/queries/src/test/org/apache/lucene/queries/payloads/TestPayloadScoreQuery.java@@ -26,7 +26,6 @@ import org.apache.lucene.analysis.Tokenizer;import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;-import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.NoMergePolicy;import org.apache.lucene.index.RandomIndexWriter;@@ -143,9 +142,9 @@ public class TestPayloadScoreQuery extends LuceneTestCase {// check includeSpanScore makes a difference heresearcher.setSimilarity(new MultiplyingSimilarity());try {- checkQuery(q, new MaxPayloadFunction(), new int[]{ 122, 222 }, new float[]{ 41.802513122558594f, 34.13160705566406f });- checkQuery(q, new MinPayloadFunction(), new int[]{ 222, 122 }, new float[]{ 34.13160705566406f, 20.901256561279297f });- checkQuery(q, new AveragePayloadFunction(), new int[] { 122, 222 }, new float[]{ 38.3189697265625f, 34.13160705566406f });+ checkQuery(q, new MaxPayloadFunction(), new int[]{ 122, 222 }, new float[]{ 20.901256561279297f, 17.06580352783203f });+ checkQuery(q, new MinPayloadFunction(), new int[]{ 222, 122 }, new float[]{ 17.06580352783203f, 10.450628280639648f });+ checkQuery(q, new AveragePayloadFunction(), new int[] { 122, 222 }, new float[]{ 19.15948486328125f, 17.06580352783203f });checkQuery(q, new MaxPayloadFunction(), false, new int[]{122, 222}, new float[]{4.0f, 4.0f});checkQuery(q, new MinPayloadFunction(), false, new int[]{222, 122}, new float[]{4.0f, 2.0f});checkQuery(q, new AveragePayloadFunction(), false, new int[]{222, 122}, new float[]{4.0f, 3.666666f});@@ -298,7 +297,7 @@ public class TestPayloadScoreQuery extends LuceneTestCase {//Make everything else 1 so we see the effect of the payload//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!@Override- public float lengthNorm(FieldInvertState state) {+ public float lengthNorm(int length) {return 1;}diff --git a/lucene/queries/src/test/org/apache/lucene/queries/payloads/TestPayloadTermQuery.java b/lucene/queries/src/test/org/apache/lucene/queries/payloads/TestPayloadTermQuery.javaindex da46a507d42..faa8dd0c138 100644--- a/lucene/queries/src/test/org/apache/lucene/queries/payloads/TestPayloadTermQuery.java+++ b/lucene/queries/src/test/org/apache/lucene/queries/payloads/TestPayloadTermQuery.java@@ -25,7 +25,6 @@ import org.apache.lucene.analysis.Tokenizer;import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;-import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;@@ -268,7 +267,7 @@ public class TestPayloadTermQuery extends LuceneTestCase {//Make everything else 1 so we see the effect of the payload//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!@Override- public float lengthNorm(FieldInvertState state) {+ public float lengthNorm(int length) {return 1;}diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/similarities/RandomSimilarity.java b/lucene/test-framework/src/java/org/apache/lucene/search/similarities/RandomSimilarity.javaindex 4bfe4b899e1..f880935339e 100644--- a/lucene/test-framework/src/java/org/apache/lucene/search/similarities/RandomSimilarity.java+++ b/lucene/test-framework/src/java/org/apache/lucene/search/similarities/RandomSimilarity.java@@ -31,7 +31,7 @@ import java.util.Random;* for the same field.*/public class RandomSimilarity extends PerFieldSimilarityWrapper {- final ClassicSimilarity defaultSim = new ClassicSimilarity();+ final BM25Similarity defaultSim = new BM25Similarity();final List<Similarity> knownSims;Map<String,Similarity> previousMappings = new HashMap<>();final int perFieldSeed;diff --git a/solr/core/src/test/org/apache/solr/DisMaxRequestHandlerTest.java b/solr/core/src/test/org/apache/solr/DisMaxRequestHandlerTest.javaindex a8070fa3b7a..8d1b758c87c 100644--- a/solr/core/src/test/org/apache/solr/DisMaxRequestHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/DisMaxRequestHandlerTest.java@@ -86,8 +86,8 @@ public class DisMaxRequestHandlerTest extends SolrTestCaseJ4 {req("cool stuff"),"//*[@numFound='3']","//result/doc[1]/int[@name='id'][.='42']"- ,"//result/doc[2]/int[@name='id'][.='8675309']"- ,"//result/doc[3]/int[@name='id'][.='666']"+ ,"//result/doc[2]/int[@name='id'][.='666']"+ ,"//result/doc[3]/int[@name='id'][.='8675309']");assertQ("multi qf",diff --git a/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.javaindex f11300432c4..f439e87a8d2 100644--- a/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java+++ b/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java@@ -97,8 +97,8 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {CommonParams.FL, "id, score, [elevated]"), "//*[@numFound='3']", "//result/doc[1]/float[@name='id'][.='7.0']"- , "//result/doc[2]/float[@name='id'][.='8.0']"- , "//result/doc[3]/float[@name='id'][.='9.0']",+ , "//result/doc[2]/float[@name='id'][.='9.0']"+ , "//result/doc[3]/float[@name='id'][.='8.0']","//result/doc[1]/bool[@name='[elevated]'][.='true']","//result/doc[2]/bool[@name='[elevated]'][.='false']","//result/doc[3]/bool[@name='[elevated]'][.='false']"diff --git a/solr/core/src/test/org/apache/solr/search/TestPayloadScoreQParserPlugin.java b/solr/core/src/test/org/apache/solr/search/TestPayloadScoreQParserPlugin.javaindex 34017c15b76..8ac09bb6530 100644--- a/solr/core/src/test/org/apache/solr/search/TestPayloadScoreQParserPlugin.java+++ b/solr/core/src/test/org/apache/solr/search/TestPayloadScoreQParserPlugin.java@@ -49,6 +49,6 @@ public class TestPayloadScoreQParserPlugin extends SolrTestCaseJ4 {// TODO: fix this includeSpanScore test to be less brittle - score result is score of "A" (via BM25) multipled by 1.0 (payload value)assertQ(req("fl","*,score", "q", "{!payload_score f=vals_dpf v=A func=min}"), "//float[@name='score']='1.0'");- assertQ(req("fl","*,score", "q", "{!payload_score f=vals_dpf v=A func=min includeSpanScore=true}"), "//float[@name='score']='0.25811607'");+ assertQ(req("fl","*,score", "q", "{!payload_score f=vals_dpf v=A func=min includeSpanScore=true}"), "//float[@name='score']='0.2876821'");}}diff --git a/solr/core/src/test/org/apache/solr/search/function/SortByFunctionTest.java b/solr/core/src/test/org/apache/solr/search/function/SortByFunctionTest.javaindex e28c95719c4..58a1b533e86 100644--- a/solr/core/src/test/org/apache/solr/search/function/SortByFunctionTest.java+++ b/solr/core/src/test/org/apache/solr/search/function/SortByFunctionTest.java@@ -65,9 +65,9 @@ public class SortByFunctionTest extends AbstractSolrTestCase {assertQ(req("fl", "id,score", "q", "f_t:ipod", "sort", "score desc"),"//*[@numFound='4']","//result/doc[1]/int[@name='id'][.='1']",- "//result/doc[2]/int[@name='id'][.='4']",- "//result/doc[3]/int[@name='id'][.='2']",- "//result/doc[4]/int[@name='id'][.='3']"+ "//result/doc[2]/int[@name='id'][.='2']",+ "//result/doc[3]/int[@name='id'][.='3']",+ "//result/doc[4]/int[@name='id'][.='4']");diff --git a/solr/core/src/test/org/apache/solr/search/function/TestFunctionQuery.java b/solr/core/src/test/org/apache/solr/search/function/TestFunctionQuery.javaindex 8aae74c56d0..e77c4ee12dc 100644--- a/solr/core/src/test/org/apache/solr/search/function/TestFunctionQuery.java+++ b/solr/core/src/test/org/apache/solr/search/function/TestFunctionQuery.java@@ -25,7 +25,6 @@ import java.util.Arrays;import java.util.List;import java.util.Random;-import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.search.similarities.Similarity;import org.apache.lucene.search.similarities.TFIDFSimilarity;import org.apache.solr.SolrTestCaseJ4;@@ -431,12 +430,8 @@ public class TestFunctionQuery extends SolrTestCaseJ4 {assertQ(req("fl","*,score","q", "{!func}tf(a_tfidf,cow)", "fq","id:6"),"//float[@name='score']='" + similarity.tf(5) + "'");- FieldInvertState state = new FieldInvertState("a_tfidf");- state.setLength(4);- long norm = similarity.computeNorm(state);- float nrm = similarity.decodeNormValue((byte) norm);assertQ(req("fl","*,score","q", "{!func}norm(a_tfidf)", "fq","id:2"),- "//float[@name='score']='" + nrm + "'"); // sqrt(4)==2 and is exactly representable when quantized to a byte+ "//float[@name='score']='0.5'"); // 1/sqrt(4)==1/2==0.5}diff --git a/solr/core/src/test/org/apache/solr/search/similarities/TestSweetSpotSimilarityFactory.java b/solr/core/src/test/org/apache/solr/search/similarities/TestSweetSpotSimilarityFactory.javaindex 4b5503d58cf..52d6f8d4c04 100644--- a/solr/core/src/test/org/apache/solr/search/similarities/TestSweetSpotSimilarityFactory.java+++ b/solr/core/src/test/org/apache/solr/search/similarities/TestSweetSpotSimilarityFactory.java@@ -16,8 +16,22 @@*/package org.apache.solr.search.similarities;+import java.io.IOException;+import java.util.Collections;+import java.util.stream.Collectors;+import java.util.stream.IntStream;++import org.apache.lucene.document.Field.Store;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.Term;import org.apache.lucene.misc.SweetSpotSimilarity;+import org.apache.lucene.search.Explanation;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.similarities.ClassicSimilarity;+import org.apache.lucene.search.similarities.Similarity;+import org.apache.lucene.store.Directory;import org.junit.BeforeClass;/**@@ -28,7 +42,38 @@ public class TestSweetSpotSimilarityFactory extends BaseSimilarityTestCase {public static void beforeClass() throws Exception {initCore("solrconfig-basic.xml","schema-sweetspot.xml");}-++ private static float computeNorm(Similarity sim, int length) throws IOException {+ String value = IntStream.range(0, length).mapToObj(i -> "a").collect(Collectors.joining(" "));+ Directory dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig().setSimilarity(sim));+ w.addDocument(Collections.singleton(newTextField("foo", value, Store.NO)));+ DirectoryReader reader = DirectoryReader.open(w);+ w.close();+ IndexSearcher searcher = new IndexSearcher(reader);+ searcher.setSimilarity(sim);+ Explanation expl = searcher.explain(new TermQuery(new Term("foo", "a")), 0);+ reader.close();+ dir.close();+ Explanation norm = findExplanation(expl, "fieldNorm");+ assertNotNull(norm);+ return norm.getValue();+ }++ private static Explanation findExplanation(Explanation expl, String text) {+ if (expl.getDescription().startsWith(text)) {+ return expl;+ } else {+ for (Explanation sub : expl.getDetails()) {+ Explanation match = findExplanation(sub, text);+ if (match != null) {+ return match;+ }+ }+ }+ return null;+ }+/** default parameters */public void testDefaults() throws Exception {SweetSpotSimilarity sim = getSimilarity("text", SweetSpotSimilarity.class);@@ -40,9 +85,9 @@ public class TestSweetSpotSimilarityFactory extends BaseSimilarityTestCase {}// default norm sanity check- assertEquals("norm 1", 1.00F, sim.computeLengthNorm(1), 0.0F);- assertEquals("norm 4", 0.50F, sim.computeLengthNorm(4), 0.0F);- assertEquals("norm 16", 0.25F, sim.computeLengthNorm(16), 0.0F);+ assertEquals("norm 1", 1.00F, computeNorm(sim, 1), 0.0F);+ assertEquals("norm 4", 0.50F, computeNorm(sim, 4), 0.0F);+ assertEquals("norm 16", 0.25F, computeNorm(sim, 16), 0.0F);}/** baseline with parameters */@@ -65,17 +110,17 @@ public class TestSweetSpotSimilarityFactory extends BaseSimilarityTestCase {// norms: plateau from 3-5assertEquals("norm 1 == 7",- sim.computeLengthNorm(1), sim.computeLengthNorm(7), 0.0F);+ computeNorm(sim, 1), computeNorm(sim, 7), 0.0F);assertEquals("norm 2 == 6",- sim.computeLengthNorm(1), sim.computeLengthNorm(7), 0.0F);- assertEquals("norm 3", 1.00F, sim.computeLengthNorm(3), 0.0F);- assertEquals("norm 4", 1.00F, sim.computeLengthNorm(4), 0.0F);- assertEquals("norm 5", 1.00F, sim.computeLengthNorm(5), 0.0F);- assertTrue("norm 6 too high: " + sim.computeLengthNorm(6),- sim.computeLengthNorm(6) < 1.0F);+ computeNorm(sim, 1), computeNorm(sim, 7), 0.0F);+ assertEquals("norm 3", 1.00F, computeNorm(sim, 3), 0.0F);+ assertEquals("norm 4", 1.00F, computeNorm(sim, 4), 0.0F);+ assertEquals("norm 5", 1.00F, computeNorm(sim, 5), 0.0F);+ assertTrue("norm 6 too high: " + computeNorm(sim, 6),+ computeNorm(sim, 6) < 1.0F);assertTrue("norm 7 higher then norm 6",- sim.computeLengthNorm(7) < sim.computeLengthNorm(6));- assertEquals("norm 20", 0.25F, sim.computeLengthNorm(20), 0.0F);+ computeNorm(sim, 7) < computeNorm(sim, 6));+ assertEquals("norm 20", 0.25F, computeNorm(sim, 20), 0.0F);}/** hyperbolic with parameters */@@ -92,16 +137,16 @@ public class TestSweetSpotSimilarityFactory extends BaseSimilarityTestCase {assertEquals("MID tf", 3.3F+(7.7F - 3.3F)/2.0F, sim.tf(5), 0.00001F);// norms: plateau from 1-5, shallow slope- assertEquals("norm 1", 1.00F, sim.computeLengthNorm(1), 0.0F);- assertEquals("norm 2", 1.00F, sim.computeLengthNorm(2), 0.0F);- assertEquals("norm 3", 1.00F, sim.computeLengthNorm(3), 0.0F);- assertEquals("norm 4", 1.00F, sim.computeLengthNorm(4), 0.0F);- assertEquals("norm 5", 1.00F, sim.computeLengthNorm(5), 0.0F);- assertTrue("norm 6 too high: " + sim.computeLengthNorm(6),- sim.computeLengthNorm(6) < 1.0F);+ assertEquals("norm 1", 1.00F, computeNorm(sim, 1), 0.0F);+ assertEquals("norm 2", 1.00F, computeNorm(sim, 2), 0.0F);+ assertEquals("norm 3", 1.00F, computeNorm(sim, 3), 0.0F);+ assertEquals("norm 4", 1.00F, computeNorm(sim, 4), 0.0F);+ assertEquals("norm 5", 1.00F, computeNorm(sim, 5), 0.0F);+ assertTrue("norm 6 too high: " + computeNorm(sim, 6),+ computeNorm(sim, 6) < 1.0F);assertTrue("norm 7 higher then norm 6",- sim.computeLengthNorm(7) < sim.computeLengthNorm(6));- assertTrue("norm 20 not high enough: " + sim.computeLengthNorm(20),- 0.25F < sim.computeLengthNorm(20));+ computeNorm(sim, 7) < computeNorm(sim, 6));+ assertTrue("norm 20 not high enough: " + computeNorm(sim, 20),+ 0.25F < computeNorm(sim, 20));}}