1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
|
/*****************************************************************************
Copyright (c) 2007, 2018, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2017, 2019, MariaDB Corporation.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
*****************************************************************************/
/**************************************************//**
@file fts/fts0que.cc
Full Text Search functionality.
Created 2007/03/27 Sunny Bains
Completed 2011/7/10 Sunny and Jimmy Yang
*******************************************************/
#include "dict0dict.h" /* dict_table_get_n_rows() */
#include "ut0rbt.h"
#include "row0sel.h"
#include "fts0fts.h"
#include "fts0priv.h"
#include "fts0ast.h"
#include "fts0pars.h"
#include "fts0types.h"
#include "ha_prototypes.h"
#include <ctype.h>
#ifndef UNIV_NONINL
#include "fts0types.ic"
#include "fts0vlc.ic"
#endif
#include <vector>
#define FTS_ELEM(t, n, i, j) (t[(i) * n + (j)])
#define RANK_DOWNGRADE (-1.0F)
#define RANK_UPGRADE (1.0F)
/* Maximum number of words supported in a phrase or proximity search. */
#define MAX_PROXIMITY_ITEM 128
/* Memory used by rbt itself for create and node add */
#define SIZEOF_RBT_CREATE sizeof(ib_rbt_t) + sizeof(ib_rbt_node_t) * 2
#define SIZEOF_RBT_NODE_ADD sizeof(ib_rbt_node_t)
/*Initial byte length for 'words' in fts_ranking_t */
#define RANKING_WORDS_INIT_LEN 4
// FIXME: Need to have a generic iterator that traverses the ilist.
typedef std::vector<fts_string_t> word_vector_t;
struct fts_word_freq_t;
/** State of an FTS query. */
struct fts_query_t {
mem_heap_t* heap; /*!< Heap to use for allocations */
trx_t* trx; /*!< The query transaction */
dict_index_t* index; /*!< The FTS index to search */
/*!< FTS auxiliary common table def */
fts_table_t fts_common_table;
fts_table_t fts_index_table;/*!< FTS auxiliary index table def */
size_t total_size; /*!< total memory size used by query */
fts_doc_ids_t* deleted; /*!< Deleted doc ids that need to be
filtered from the output */
fts_ast_node_t* root; /*!< Abstract syntax tree */
fts_ast_node_t* cur_node; /*!< Current tree node */
ib_rbt_t* word_map; /*!< Matched word map for
searching by word*/
word_vector_t* word_vector; /*!< Matched word vector for
searching by index */
ib_rbt_t* doc_ids; /*!< The current set of matching
doc ids, elements are of
type fts_ranking_t */
ib_rbt_t* intersection; /*!< The doc ids that were found in
doc_ids, this tree will become
the new doc_ids, elements are of type
fts_ranking_t */
/*!< Prepared statement to read the
nodes from the FTS INDEX */
que_t* read_nodes_graph;
fts_ast_oper_t oper; /*!< Current boolean mode operator */
/*!< TRUE if we want to collect the
word positions within the document */
ibool collect_positions;
ulint flags; /*!< Specify the full text search type,
such as boolean search, phrase
search, proximity search etc. */
ulint distance; /*!< The proximity distance of a
phrase search. */
/*!< These doc ids are used as a
boundary condition when searching the
FTS index rows */
doc_id_t lower_doc_id; /*!< Lowest doc id in doc_ids */
doc_id_t upper_doc_id; /*!< Highest doc id in doc_ids */
bool boolean_mode; /*!< TRUE if boolean mode query */
ib_vector_t* matched; /*!< Array of matching documents
(fts_match_t) to search for a phrase */
ib_vector_t** match_array; /*!< Used for proximity search, contains
position info for each matched word
in the word list */
ib_uint64_t total_docs; /*!< The total number of documents */
ulint total_words; /*!< The total number of words */
dberr_t error; /*!< Error code if any, that is
encountered during query processing */
ib_rbt_t* word_freqs; /*!< RB tree of word frequencies per
document, its elements are of type
fts_word_freq_t */
bool multi_exist; /*!< multiple FTS_EXIST oper */
};
/** For phrase matching, first we collect the documents and the positions
then we match. */
struct fts_match_t {
doc_id_t doc_id; /*!< Document id */
ulint start; /*!< Start the phrase match from
this offset within the positions
vector. */
ib_vector_t* positions; /*!< Offsets of a word in a
document */
};
/** For matching tokens in a phrase search. We use this data structure in
the callback that determines whether a document should be accepted or
rejected for a phrase search. */
struct fts_select_t {
doc_id_t doc_id; /*!< The document id to match */
ulint min_pos; /*!< For found to be TRUE at least
one position must be greater than
min_pos. */
ibool found; /*!< TRUE if found */
fts_word_freq_t*
word_freq; /*!< Word frequency instance of the
current word being looked up in
the FTS index */
};
typedef std::vector<ulint> pos_vector_t;
/** structure defines a set of ranges for original documents, each of which
has a minimum position and maximum position. Text in such range should
contain all words in the proximity search. We will need to count the
words in such range to make sure it is less than the specified distance
of the proximity search */
struct fts_proximity_t {
ulint n_pos; /*!< number of position set, defines
a range (min to max) containing all
matching words */
pos_vector_t min_pos; /*!< the minimum position (in bytes)
of the range */
pos_vector_t max_pos; /*!< the maximum position (in bytes)
of the range */
};
/** The match positions and tokesn to match */
struct fts_phrase_t {
ibool found; /*!< Match result */
const fts_match_t*
match; /*!< Positions within text */
const ib_vector_t*
tokens; /*!< Tokens to match */
ulint distance; /*!< For matching on proximity
distance. Can be 0 for exact match */
CHARSET_INFO* charset; /*!< Phrase match charset */
mem_heap_t* heap; /*!< Heap for word processing */
ulint zip_size; /*!< row zip size */
fts_proximity_t*proximity_pos; /*!< position info for proximity
search verification. Records the min
and max position of words matched */
};
/** For storing the frequncy of a word/term in a document */
struct fts_doc_freq_t {
doc_id_t doc_id; /*!< Document id */
ulint freq; /*!< Frequency of a word in a document */
};
/** To determine the word frequency per document. */
struct fts_word_freq_t {
fts_string_t word; /*!< Word for which we need the freq,
it's allocated on the query heap */
ib_rbt_t* doc_freqs; /*!< RB Tree for storing per document
word frequencies. The elements are
of type fts_doc_freq_t */
ib_uint64_t doc_count; /*!< Total number of documents that
contain this word */
double idf; /*!< Inverse document frequency */
};
/********************************************************************
Callback function to fetch the rows in an FTS INDEX record.
@return always TRUE */
static
ibool
fts_query_index_fetch_nodes(
/*========================*/
void* row, /*!< in: sel_node_t* */
void* user_arg); /*!< in: pointer to ib_vector_t */
/********************************************************************
Read and filter nodes.
@return fts_node_t instance */
static
dberr_t
fts_query_filter_doc_ids(
/*=====================*/
fts_query_t* query, /*!< in: query instance */
const fts_string_t* word, /*!< in: the current word */
fts_word_freq_t* word_freq, /*!< in/out: word frequency */
const fts_node_t* node, /*!< in: current FTS node */
void* data, /*!< in: doc id ilist */
ulint len, /*!< in: doc id ilist size */
ibool calc_doc_count);/*!< in: whether to remember doc
count */
#if 0
/*****************************************************************//***
Find a doc_id in a word's ilist.
@return TRUE if found. */
static
ibool
fts_query_find_doc_id(
/*==================*/
fts_select_t* select, /*!< in/out: search the doc id selected,
update the frequency if found. */
void* data, /*!< in: doc id ilist */
ulint len); /*!< in: doc id ilist size */
#endif
/*************************************************************//**
This function implements a simple "blind" query expansion search:
words in documents found in the first search pass will be used as
search arguments to search the document again, thus "expand"
the search result set.
@return DB_SUCCESS if success, otherwise the error code */
static
dberr_t
fts_expand_query(
/*=============*/
dict_index_t* index, /*!< in: FTS index to search */
fts_query_t* query) /*!< in: query result, to be freed
by the client */
MY_ATTRIBUTE((nonnull, warn_unused_result));
/*************************************************************//**
This function finds documents that contain all words in a
phrase or proximity search. And if proximity search, verify
the words are close enough to each other, as in specified distance.
This function is called for phrase and proximity search.
@return TRUE if documents are found, FALSE if otherwise */
static
ibool
fts_phrase_or_proximity_search(
/*===========================*/
fts_query_t* query, /*!< in/out: query instance
query->doc_ids might be instantiated
with qualified doc IDs */
ib_vector_t* tokens); /*!< in: Tokens contain words */
/*************************************************************//**
This function checks whether words in result documents are close to
each other (within proximity range as specified by "distance").
If "distance" is MAX_ULINT, then it will find all combinations of
positions of matching words and store min and max positions
in the "qualified_pos" for later verification.
@return true if words are close to each other, false if otherwise */
static
bool
fts_proximity_get_positions(
/*========================*/
fts_match_t** match, /*!< in: query instance */
ulint num_match, /*!< in: number of matching
items */
ulint distance, /*!< in: distance value
for proximity search */
fts_proximity_t* qualified_pos); /*!< out: the position info
records ranges containing
all matching words. */
#if 0
/********************************************************************
Get the total number of words in a documents. */
static
ulint
fts_query_terms_in_document(
/*========================*/
/*!< out: DB_SUCCESS if all go well
else error code */
fts_query_t* query, /*!< in: FTS query state */
doc_id_t doc_id, /*!< in: the word to check */
ulint* total); /*!< out: total words in document */
#endif
/********************************************************************
Compare two fts_doc_freq_t doc_ids.
@return < 0 if n1 < n2, 0 if n1 == n2, > 0 if n1 > n2 */
UNIV_INLINE
int
fts_freq_doc_id_cmp(
/*================*/
const void* p1, /*!< in: id1 */
const void* p2) /*!< in: id2 */
{
const fts_doc_freq_t* fq1 = (const fts_doc_freq_t*) p1;
const fts_doc_freq_t* fq2 = (const fts_doc_freq_t*) p2;
return((int) (fq1->doc_id - fq2->doc_id));
}
#if 0
/*******************************************************************//**
Print the table used for calculating LCS. */
static
void
fts_print_lcs_table(
/*================*/
const ulint* table, /*!< in: array to print */
ulint n_rows, /*!< in: total no. of rows */
ulint n_cols) /*!< in: total no. of cols */
{
ulint i;
for (i = 0; i < n_rows; ++i) {
ulint j;
printf("\n");
for (j = 0; j < n_cols; ++j) {
printf("%2lu ", FTS_ELEM(table, n_cols, i, j));
}
}
}
/********************************************************************
Find the longest common subsequence between the query string and
the document. */
static
ulint
fts_query_lcs(
/*==========*/
/*!< out: LCS (length) between
two ilists */
const ulint* p1, /*!< in: word positions of query */
ulint len_p1, /*!< in: no. of elements in p1 */
const ulint* p2, /*!< in: word positions within document */
ulint len_p2) /*!< in: no. of elements in p2 */
{
int i;
ulint len = 0;
ulint r = len_p1;
ulint c = len_p2;
ulint size = (r + 1) * (c + 1) * sizeof(ulint);
ulint* table = (ulint*) ut_malloc(size);
/* Traverse the table backwards, from the last row to the first and
also from the last column to the first. We compute the smaller
common subsequeces first, then use the caluclated values to determine
the longest common subsequence. The result will be in TABLE[0][0]. */
for (i = r; i >= 0; --i) {
int j;
for (j = c; j >= 0; --j) {
if (p1[i] == (ulint) -1 || p2[j] == (ulint) -1) {
FTS_ELEM(table, c, i, j) = 0;
} else if (p1[i] == p2[j]) {
FTS_ELEM(table, c, i, j) = FTS_ELEM(
table, c, i + 1, j + 1) + 1;
} else {
ulint value;
value = ut_max(
FTS_ELEM(table, c, i + 1, j),
FTS_ELEM(table, c, i, j + 1));
FTS_ELEM(table, c, i, j) = value;
}
}
}
len = FTS_ELEM(table, c, 0, 0);
fts_print_lcs_table(table, r, c);
printf("\nLen=%lu\n", len);
ut_free(table);
return(len);
}
#endif
/*******************************************************************//**
Compare two fts_ranking_t instance on their rank value and doc ids in
descending order on the rank and ascending order on doc id.
@return 0 if p1 == p2, < 0 if p1 < p2, > 0 if p1 > p2 */
static
int
fts_query_compare_rank(
/*===================*/
const void* p1, /*!< in: pointer to elem */
const void* p2) /*!< in: pointer to elem */
{
const fts_ranking_t* r1 = (const fts_ranking_t*) p1;
const fts_ranking_t* r2 = (const fts_ranking_t*) p2;
if (r2->rank < r1->rank) {
return(-1);
} else if (r2->rank == r1->rank) {
if (r1->doc_id < r2->doc_id) {
return(1);
} else if (r1->doc_id > r2->doc_id) {
return(1);
}
return(0);
}
return(1);
}
#ifdef FTS_UTF8_DEBUG
/*******************************************************************//**
Convert string to lowercase.
@return lower case string, callers responsibility to delete using
ut_free() */
static
byte*
fts_tolower(
/*========*/
const byte* src, /*!< in: src string */
ulint len) /*!< in: src string length */
{
fts_string_t str;
byte* lc_str = ut_malloc(len + 1);
str.f_len = len;
str.f_str = lc_str;
memcpy(str.f_str, src, len);
/* Make sure the last byte is NUL terminated */
str.f_str[len] = '\0';
fts_utf8_tolower(&str);
return(lc_str);
}
/*******************************************************************//**
Do a case insensitive search. Doesn't check for NUL byte end marker
only relies on len. Convert str2 to lower case before comparing.
@return 0 if p1 == p2, < 0 if p1 < p2, > 0 if p1 > p2 */
static
int
fts_utf8_strcmp(
/*============*/
const fts_string_t*
str1, /*!< in: should be lower case*/
fts_string_t* str2) /*!< in: any case. We will use the length
of this string during compare as it
should be the min of the two strings */
{
byte b = str2->f_str[str2->f_len];
ut_a(str2->f_len <= str1->f_len);
/* We need to write a NUL byte at the end of the string because the
string is converted to lowercase by a MySQL function which doesn't
care about the length. */
str2->f_str[str2->f_len] = 0;
fts_utf8_tolower(str2);
/* Restore the value we replaced above. */
str2->f_str[str2->f_len] = b;
return(memcmp(str1->f_str, str2->f_str, str2->f_len));
}
#endif
/*******************************************************************//**
Create words in ranking */
static
void
fts_ranking_words_create(
/*=====================*/
fts_query_t* query, /*!< in: query instance */
fts_ranking_t* ranking) /*!< in: ranking instance */
{
ranking->words = static_cast<byte*>(
mem_heap_zalloc(query->heap, RANKING_WORDS_INIT_LEN));
ranking->words_len = RANKING_WORDS_INIT_LEN;
}
/*
The optimization here is using a char array(bitmap) to replace words rb tree
in fts_ranking_t.
It can save lots of memory except in some cases of QUERY EXPANSION.
'word_map' is used as a word dictionary, in which the key is a word, the value
is a number. In 'fts_ranking_words_add', we first check if the word is in 'word_map'.
if not, we add it into 'word_map', and give it a position(actually a number).
then we set the corresponding bit to '1' at the position in the char array 'words'.
'word_vector' is a useful backup of 'word_map', and we can get a word by its position,
more quickly than searching by value in 'word_map'. we use 'word_vector'
in 'fts_query_calculate_ranking' and 'fts_expand_query'. In the two functions, we need
to scan the bitmap 'words', and get a word when a bit is '1', then we get word_freq
by the word.
*/
/*******************************************************************//**
Add a word into ranking */
static
void
fts_ranking_words_add(
/*==================*/
fts_query_t* query, /*!< in: query instance */
fts_ranking_t* ranking, /*!< in: ranking instance */
const fts_string_t* word) /*!< in: term/word to add */
{
ulint pos;
ulint byte_offset;
ulint bit_offset;
ib_rbt_bound_t parent;
/* Note: we suppose the word map and vector are append-only. */
ut_ad(query->word_vector->size() == rbt_size(query->word_map));
/* We use ib_rbt to simulate a map, f_n_char means position. */
if (rbt_search(query->word_map, &parent, word) == 0) {
fts_string_t* result_word;
result_word = rbt_value(fts_string_t, parent.last);
pos = result_word->f_n_char;
ut_ad(pos < rbt_size(query->word_map));
} else {
/* Add the word to map. */
fts_string_t new_word;
pos = rbt_size(query->word_map);
new_word.f_str = static_cast<byte*>(mem_heap_alloc(query->heap,
word->f_len + 1));
memcpy(new_word.f_str, word->f_str, word->f_len);
new_word.f_str[word->f_len] = 0;
new_word.f_len = word->f_len;
new_word.f_n_char = pos;
rbt_add_node(query->word_map, &parent, &new_word);
ut_ad(rbt_validate(query->word_map));
query->word_vector->push_back(new_word);
}
/* Check words len */
byte_offset = pos / CHAR_BIT;
if (byte_offset >= ranking->words_len) {
byte* words = ranking->words;
ulint words_len = ranking->words_len;
while (byte_offset >= words_len) {
words_len *= 2;
}
ranking->words = static_cast<byte*>(
mem_heap_zalloc(query->heap, words_len));
ut_memcpy(ranking->words, words, ranking->words_len);
ranking->words_len = words_len;
}
/* Set ranking words */
ut_ad(byte_offset < ranking->words_len);
bit_offset = pos % CHAR_BIT;
ranking->words[byte_offset] |= 1 << bit_offset;
}
/*******************************************************************//**
Get a word from a ranking
@return true if it's successful */
static
bool
fts_ranking_words_get_next(
/*=======================*/
const fts_query_t* query, /*!< in: query instance */
fts_ranking_t* ranking,/*!< in: ranking instance */
ulint* pos, /*!< in/out: word start pos */
fts_string_t* word) /*!< in/out: term/word to add */
{
bool ret = false;
ulint max_pos = ranking->words_len * CHAR_BIT;
/* Search for next word */
while (*pos < max_pos) {
ulint byte_offset = *pos / CHAR_BIT;
ulint bit_offset = *pos % CHAR_BIT;
if (ranking->words[byte_offset] & (1 << bit_offset)) {
ret = true;
break;
}
*pos += 1;
};
/* Get next word from word vector */
if (ret) {
ut_ad(*pos < query->word_vector->size());
*word = query->word_vector->at((size_t)*pos);
*pos += 1;
}
return ret;
}
/*******************************************************************//**
Add a word if it doesn't exist, to the term freq RB tree. We store
a pointer to the word that is passed in as the argument.
@return pointer to word */
static
fts_word_freq_t*
fts_query_add_word_freq(
/*====================*/
fts_query_t* query, /*!< in: query instance */
const fts_string_t* word) /*!< in: term/word to add */
{
ib_rbt_bound_t parent;
/* Lookup the word in our rb tree and add if it doesn't exist. */
if (rbt_search(query->word_freqs, &parent, word) != 0) {
fts_word_freq_t word_freq;
memset(&word_freq, 0, sizeof(word_freq));
word_freq.word.f_str = static_cast<byte*>(
mem_heap_alloc(query->heap, word->f_len + 1));
memcpy(word_freq.word.f_str, word->f_str, word->f_len);
word_freq.word.f_str[word->f_len] = 0;
word_freq.word.f_len = word->f_len;
word_freq.doc_count = 0;
word_freq.doc_freqs = rbt_create(
sizeof(fts_doc_freq_t), fts_freq_doc_id_cmp);
parent.last = rbt_add_node(
query->word_freqs, &parent, &word_freq);
query->total_size += word->f_len
+ SIZEOF_RBT_CREATE
+ SIZEOF_RBT_NODE_ADD
+ sizeof(fts_word_freq_t);
}
return(rbt_value(fts_word_freq_t, parent.last));
}
/*******************************************************************//**
Add a doc id if it doesn't exist, to the doc freq RB tree.
@return pointer to word */
static
fts_doc_freq_t*
fts_query_add_doc_freq(
/*===================*/
fts_query_t* query, /*!< in: query instance */
ib_rbt_t* doc_freqs, /*!< in: rb tree of fts_doc_freq_t */
doc_id_t doc_id) /*!< in: doc id to add */
{
ib_rbt_bound_t parent;
/* Lookup the doc id in our rb tree and add if it doesn't exist. */
if (rbt_search(doc_freqs, &parent, &doc_id) != 0) {
fts_doc_freq_t doc_freq;
memset(&doc_freq, 0, sizeof(doc_freq));
doc_freq.freq = 0;
doc_freq.doc_id = doc_id;
parent.last = rbt_add_node(doc_freqs, &parent, &doc_freq);
query->total_size += SIZEOF_RBT_NODE_ADD
+ sizeof(fts_doc_freq_t);
}
return(rbt_value(fts_doc_freq_t, parent.last));
}
/*******************************************************************//**
Add the doc id to the query set only if it's not in the
deleted array. */
static
void
fts_query_union_doc_id(
/*===================*/
fts_query_t* query, /*!< in: query instance */
doc_id_t doc_id, /*!< in: the doc id to add */
fts_rank_t rank) /*!< in: if non-zero, it is the
rank associated with the doc_id */
{
ib_rbt_bound_t parent;
ulint size = ib_vector_size(query->deleted->doc_ids);
fts_update_t* array = (fts_update_t*) query->deleted->doc_ids->data;
/* Check if the doc id is deleted and it's not already in our set. */
if (fts_bsearch(array, 0, static_cast<int>(size), doc_id) < 0
&& rbt_search(query->doc_ids, &parent, &doc_id) != 0) {
fts_ranking_t ranking;
ranking.rank = rank;
ranking.doc_id = doc_id;
fts_ranking_words_create(query, &ranking);
rbt_add_node(query->doc_ids, &parent, &ranking);
query->total_size += SIZEOF_RBT_NODE_ADD
+ sizeof(fts_ranking_t) + RANKING_WORDS_INIT_LEN;
}
}
/*******************************************************************//**
Remove the doc id from the query set only if it's not in the
deleted set. */
static
void
fts_query_remove_doc_id(
/*====================*/
fts_query_t* query, /*!< in: query instance */
doc_id_t doc_id) /*!< in: the doc id to add */
{
ib_rbt_bound_t parent;
ulint size = ib_vector_size(query->deleted->doc_ids);
fts_update_t* array = (fts_update_t*) query->deleted->doc_ids->data;
/* Check if the doc id is deleted and it's in our set. */
if (fts_bsearch(array, 0, static_cast<int>(size), doc_id) < 0
&& rbt_search(query->doc_ids, &parent, &doc_id) == 0) {
ut_free(rbt_remove_node(query->doc_ids, parent.last));
ut_ad(query->total_size >=
SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t));
query->total_size -= SIZEOF_RBT_NODE_ADD
+ sizeof(fts_ranking_t);
}
}
/*******************************************************************//**
Find the doc id in the query set but not in the deleted set, artificialy
downgrade or upgrade its ranking by a value and make/initialize its ranking
under or above its normal range 0 to 1. This is used for Boolean Search
operator such as Negation operator, which makes word's contribution to the
row's relevance to be negative */
static
void
fts_query_change_ranking(
/*====================*/
fts_query_t* query, /*!< in: query instance */
doc_id_t doc_id, /*!< in: the doc id to add */
ibool downgrade) /*!< in: Whether to downgrade ranking */
{
ib_rbt_bound_t parent;
ulint size = ib_vector_size(query->deleted->doc_ids);
fts_update_t* array = (fts_update_t*) query->deleted->doc_ids->data;
/* Check if the doc id is deleted and it's in our set. */
if (fts_bsearch(array, 0, static_cast<int>(size), doc_id) < 0
&& rbt_search(query->doc_ids, &parent, &doc_id) == 0) {
fts_ranking_t* ranking;
ranking = rbt_value(fts_ranking_t, parent.last);
ranking->rank += downgrade ? RANK_DOWNGRADE : RANK_UPGRADE;
/* Allow at most 2 adjustment by RANK_DOWNGRADE (-0.5)
and RANK_UPGRADE (0.5) */
if (ranking->rank >= 1.0F) {
ranking->rank = 1.0F;
} else if (ranking->rank <= -1.0F) {
ranking->rank = -1.0F;
}
}
}
/*******************************************************************//**
Check the doc id in the query set only if it's not in the
deleted array. The doc ids that were found are stored in
another rb tree (fts_query_t::intersect). */
static
void
fts_query_intersect_doc_id(
/*=======================*/
fts_query_t* query, /*!< in: query instance */
doc_id_t doc_id, /*!< in: the doc id to add */
fts_rank_t rank) /*!< in: if non-zero, it is the
rank associated with the doc_id */
{
ib_rbt_bound_t parent;
ulint size = ib_vector_size(query->deleted->doc_ids);
fts_update_t* array = (fts_update_t*) query->deleted->doc_ids->data;
fts_ranking_t* ranking= NULL;
/* There are three types of intersect:
1. '+a': doc_ids is empty, add doc into intersect if it matches 'a'.
2. 'a +b': docs match 'a' is in doc_ids, add doc into intersect
if it matches 'b'. if the doc is also in doc_ids, then change the
doc's rank, and add 'a' in doc's words.
3. '+a +b': docs matching '+a' is in doc_ids, add doc into intsersect
if it matches 'b' and it's in doc_ids.(multi_exist = true). */
/* Check if the doc id is deleted and it's in our set */
if (fts_bsearch(array, 0, static_cast<int>(size), doc_id) < 0) {
fts_ranking_t new_ranking;
if (rbt_search(query->doc_ids, &parent, &doc_id) != 0) {
if (query->multi_exist) {
return;
} else {
new_ranking.words = NULL;
}
} else {
ranking = rbt_value(fts_ranking_t, parent.last);
/* We've just checked the doc id before */
if (ranking->words == NULL) {
ut_ad(rbt_search(query->intersection, &parent,
ranking) == 0);
return;
}
/* Merge rank */
rank += ranking->rank;
if (rank >= 1.0F) {
rank = 1.0F;
} else if (rank <= -1.0F) {
rank = -1.0F;
}
/* Take words */
new_ranking.words = ranking->words;
new_ranking.words_len = ranking->words_len;
}
new_ranking.rank = rank;
new_ranking.doc_id = doc_id;
if (rbt_search(query->intersection, &parent,
&new_ranking) != 0) {
if (new_ranking.words == NULL) {
fts_ranking_words_create(query, &new_ranking);
query->total_size += RANKING_WORDS_INIT_LEN;
} else {
/* Note that the intersection has taken
ownership of the ranking data. */
ranking->words = NULL;
}
rbt_add_node(query->intersection,
&parent, &new_ranking);
query->total_size += SIZEOF_RBT_NODE_ADD
+ sizeof(fts_ranking_t);
}
}
}
/*******************************************************************//**
Free the document ranking rb tree. */
static
void
fts_query_free_doc_ids(
/*===================*/
fts_query_t* query, /*!< in: query instance */
ib_rbt_t* doc_ids) /*!< in: rb tree to free */
{
const ib_rbt_node_t* node;
for (node = rbt_first(doc_ids); node; node = rbt_first(doc_ids)) {
fts_ranking_t* ranking;
ranking = rbt_value(fts_ranking_t, node);
if (ranking->words) {
ranking->words = NULL;
}
ut_free(rbt_remove_node(doc_ids, node));
ut_ad(query->total_size >=
SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t));
query->total_size -= SIZEOF_RBT_NODE_ADD
+ sizeof(fts_ranking_t);
}
rbt_free(doc_ids);
ut_ad(query->total_size >= SIZEOF_RBT_CREATE);
query->total_size -= SIZEOF_RBT_CREATE;
}
/*******************************************************************//**
Add the word to the documents "list" of matching words from
the query. We make a copy of the word from the query heap. */
static
void
fts_query_add_word_to_document(
/*===========================*/
fts_query_t* query, /*!< in: query to update */
doc_id_t doc_id, /*!< in: the document to update */
const fts_string_t* word) /*!< in: the token to add */
{
ib_rbt_bound_t parent;
fts_ranking_t* ranking = NULL;
if (query->flags == FTS_OPT_RANKING) {
return;
}
/* First we search the intersection RB tree as it could have
taken ownership of the words rb tree instance. */
if (query->intersection
&& rbt_search(query->intersection, &parent, &doc_id) == 0) {
ranking = rbt_value(fts_ranking_t, parent.last);
}
if (ranking == NULL
&& rbt_search(query->doc_ids, &parent, &doc_id) == 0) {
ranking = rbt_value(fts_ranking_t, parent.last);
}
if (ranking != NULL) {
fts_ranking_words_add(query, ranking, word);
}
}
/*******************************************************************//**
Check the node ilist. */
static
void
fts_query_check_node(
/*=================*/
fts_query_t* query, /*!< in: query to update */
const fts_string_t* token, /*!< in: the token to search */
const fts_node_t* node) /*!< in: node to check */
{
/* Skip nodes whose doc ids are out range. */
if (query->oper == FTS_EXIST
&& ((query->upper_doc_id > 0
&& node->first_doc_id > query->upper_doc_id)
|| (query->lower_doc_id > 0
&& node->last_doc_id < query->lower_doc_id))) {
/* Ignore */
} else {
int ret;
ib_rbt_bound_t parent;
ulint ilist_size = node->ilist_size;
fts_word_freq_t*word_freqs;
/* The word must exist. */
ret = rbt_search(query->word_freqs, &parent, token);
ut_a(ret == 0);
word_freqs = rbt_value(fts_word_freq_t, parent.last);
query->error = fts_query_filter_doc_ids(
query, token, word_freqs, node,
node->ilist, ilist_size, TRUE);
}
}
/*****************************************************************//**
Search index cache for word with wildcard match.
@return number of words matched */
static
ulint
fts_cache_find_wildcard(
/*====================*/
fts_query_t* query, /*!< in: query instance */
const fts_index_cache_t*index_cache, /*!< in: cache to search */
const fts_string_t* token) /*!< in: token to search */
{
ib_rbt_bound_t parent;
const ib_vector_t* nodes = NULL;
fts_string_t srch_text;
byte term[FTS_MAX_WORD_LEN + 1];
ulint num_word = 0;
srch_text.f_len = (token->f_str[token->f_len - 1] == '%')
? token->f_len - 1
: token->f_len;
strncpy((char*) term, (char*) token->f_str, srch_text.f_len);
term[srch_text.f_len] = '\0';
srch_text.f_str = term;
/* Lookup the word in the rb tree */
if (rbt_search_cmp(index_cache->words, &parent, &srch_text, NULL,
innobase_fts_text_cmp_prefix) == 0) {
const fts_tokenizer_word_t* word;
ulint i;
const ib_rbt_node_t* cur_node;
ibool forward = FALSE;
word = rbt_value(fts_tokenizer_word_t, parent.last);
cur_node = parent.last;
while (innobase_fts_text_cmp_prefix(
index_cache->charset, &srch_text, &word->text) == 0) {
nodes = word->nodes;
for (i = 0; nodes && i < ib_vector_size(nodes); ++i) {
int ret;
const fts_node_t* node;
ib_rbt_bound_t freq_parent;
fts_word_freq_t* word_freqs;
node = static_cast<const fts_node_t*>(
ib_vector_get_const(nodes, i));
ret = rbt_search(query->word_freqs,
&freq_parent,
&srch_text);
ut_a(ret == 0);
word_freqs = rbt_value(
fts_word_freq_t,
freq_parent.last);
query->error = fts_query_filter_doc_ids(
query, &srch_text,
word_freqs, node,
node->ilist, node->ilist_size, TRUE);
if (query->error != DB_SUCCESS) {
return(0);
}
}
num_word++;
if (!forward) {
cur_node = rbt_prev(
index_cache->words, cur_node);
} else {
cont_search:
cur_node = rbt_next(
index_cache->words, cur_node);
}
if (!cur_node) {
break;
}
word = rbt_value(fts_tokenizer_word_t, cur_node);
}
if (!forward) {
forward = TRUE;
cur_node = parent.last;
goto cont_search;
}
}
return(num_word);
}
/*****************************************************************//**
Set difference.
@return DB_SUCCESS if all go well */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_difference(
/*=================*/
fts_query_t* query, /*!< in: query instance */
const fts_string_t* token) /*!< in: token to search */
{
ulint n_doc_ids= 0;
trx_t* trx = query->trx;
dict_table_t* table = query->index->table;
ut_a(query->oper == FTS_IGNORE);
#ifdef FTS_INTERNAL_DIAG_PRINT
fprintf(stderr, "DIFFERENCE: Searching: '%.*s'\n",
(int) token->f_len, token->f_str);
#endif
if (query->doc_ids) {
n_doc_ids = rbt_size(query->doc_ids);
}
/* There is nothing we can substract from an empty set. */
if (query->doc_ids && !rbt_empty(query->doc_ids)) {
ulint i;
fts_fetch_t fetch;
const ib_vector_t* nodes;
const fts_index_cache_t*index_cache;
que_t* graph = NULL;
fts_cache_t* cache = table->fts->cache;
dberr_t error;
rw_lock_x_lock(&cache->lock);
index_cache = fts_find_index_cache(cache, query->index);
/* Must find the index cache */
ut_a(index_cache != NULL);
/* Search the cache for a matching word first. */
if (query->cur_node->term.wildcard
&& query->flags != FTS_PROXIMITY
&& query->flags != FTS_PHRASE) {
fts_cache_find_wildcard(query, index_cache, token);
} else {
nodes = fts_cache_find_word(index_cache, token);
for (i = 0; nodes && i < ib_vector_size(nodes)
&& query->error == DB_SUCCESS; ++i) {
const fts_node_t* node;
node = static_cast<const fts_node_t*>(
ib_vector_get_const(nodes, i));
fts_query_check_node(query, token, node);
}
}
rw_lock_x_unlock(&cache->lock);
/* error is passed by 'query->error' */
if (query->error != DB_SUCCESS) {
ut_ad(query->error == DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
return(query->error);
}
/* Setup the callback args for filtering and
consolidating the ilist. */
fetch.read_arg = query;
fetch.read_record = fts_query_index_fetch_nodes;
error = fts_index_fetch_nodes(
trx, &graph, &query->fts_index_table, token, &fetch);
/* DB_FTS_EXCEED_RESULT_CACHE_LIMIT passed by 'query->error' */
ut_ad(!(query->error != DB_SUCCESS && error != DB_SUCCESS));
if (error != DB_SUCCESS) {
query->error = error;
}
fts_que_graph_free(graph);
}
/* The size can't increase. */
ut_a(rbt_size(query->doc_ids) <= n_doc_ids);
return(query->error);
}
/*****************************************************************//**
Intersect the token doc ids with the current set.
@return DB_SUCCESS if all go well */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_intersect(
/*================*/
fts_query_t* query, /*!< in: query instance */
const fts_string_t* token) /*!< in: the token to search */
{
trx_t* trx = query->trx;
dict_table_t* table = query->index->table;
ut_a(query->oper == FTS_EXIST);
#ifdef FTS_INTERNAL_DIAG_PRINT
fprintf(stderr, "INTERSECT: Searching: '%.*s'\n",
(int) token->f_len, token->f_str);
#endif
/* If the words set is not empty and multi exist is true,
we know the intersection set is empty in advance. */
if (!(rbt_empty(query->doc_ids) && query->multi_exist)) {
ulint n_doc_ids = 0;
ulint i;
fts_fetch_t fetch;
const ib_vector_t* nodes;
const fts_index_cache_t*index_cache;
que_t* graph = NULL;
fts_cache_t* cache = table->fts->cache;
dberr_t error;
ut_a(!query->intersection);
n_doc_ids = rbt_size(query->doc_ids);
/* Create the rb tree that will hold the doc ids of
the intersection. */
query->intersection = rbt_create(
sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
query->total_size += SIZEOF_RBT_CREATE;
/* This is to avoid decompressing the ilist if the
node's ilist doc ids are out of range. */
if (!rbt_empty(query->doc_ids) && query->multi_exist) {
const ib_rbt_node_t* node;
doc_id_t* doc_id;
node = rbt_first(query->doc_ids);
doc_id = rbt_value(doc_id_t, node);
query->lower_doc_id = *doc_id;
node = rbt_last(query->doc_ids);
doc_id = rbt_value(doc_id_t, node);
query->upper_doc_id = *doc_id;
} else {
query->lower_doc_id = 0;
query->upper_doc_id = 0;
}
/* Search the cache for a matching word first. */
rw_lock_x_lock(&cache->lock);
/* Search for the index specific cache. */
index_cache = fts_find_index_cache(cache, query->index);
/* Must find the index cache. */
ut_a(index_cache != NULL);
if (query->cur_node->term.wildcard) {
/* Wildcard search the index cache */
fts_cache_find_wildcard(query, index_cache, token);
} else {
nodes = fts_cache_find_word(index_cache, token);
for (i = 0; nodes && i < ib_vector_size(nodes)
&& query->error == DB_SUCCESS; ++i) {
const fts_node_t* node;
node = static_cast<const fts_node_t*>(
ib_vector_get_const(nodes, i));
fts_query_check_node(query, token, node);
}
}
rw_lock_x_unlock(&cache->lock);
/* error is passed by 'query->error' */
if (query->error != DB_SUCCESS) {
ut_ad(query->error == DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
return(query->error);
}
/* Setup the callback args for filtering and
consolidating the ilist. */
fetch.read_arg = query;
fetch.read_record = fts_query_index_fetch_nodes;
error = fts_index_fetch_nodes(
trx, &graph, &query->fts_index_table, token, &fetch);
/* DB_FTS_EXCEED_RESULT_CACHE_LIMIT passed by 'query->error' */
ut_ad(!(query->error != DB_SUCCESS && error != DB_SUCCESS));
if (error != DB_SUCCESS) {
query->error = error;
}
fts_que_graph_free(graph);
if (query->error == DB_SUCCESS) {
/* Make the intesection (rb tree) the current doc id
set and free the old set. */
fts_query_free_doc_ids(query, query->doc_ids);
query->doc_ids = query->intersection;
query->intersection = NULL;
ut_a(!query->multi_exist || (query->multi_exist
&& rbt_size(query->doc_ids) <= n_doc_ids));
}
}
return(query->error);
}
/*****************************************************************//**
Query index cache.
@return DB_SUCCESS if all go well */
static
dberr_t
fts_query_cache(
/*============*/
fts_query_t* query, /*!< in/out: query instance */
const fts_string_t* token) /*!< in: token to search */
{
const fts_index_cache_t*index_cache;
dict_table_t* table = query->index->table;
fts_cache_t* cache = table->fts->cache;
/* Search the cache for a matching word first. */
rw_lock_x_lock(&cache->lock);
/* Search for the index specific cache. */
index_cache = fts_find_index_cache(cache, query->index);
/* Must find the index cache. */
ut_a(index_cache != NULL);
if (query->cur_node->term.wildcard
&& query->flags != FTS_PROXIMITY
&& query->flags != FTS_PHRASE) {
/* Wildcard search the index cache */
fts_cache_find_wildcard(query, index_cache, token);
} else {
const ib_vector_t* nodes;
ulint i;
nodes = fts_cache_find_word(index_cache, token);
for (i = 0; nodes && i < ib_vector_size(nodes)
&& query->error == DB_SUCCESS; ++i) {
const fts_node_t* node;
node = static_cast<const fts_node_t*>(
ib_vector_get_const(nodes, i));
fts_query_check_node(query, token, node);
}
}
rw_lock_x_unlock(&cache->lock);
return(query->error);
}
/*****************************************************************//**
Set union.
@return DB_SUCCESS if all go well */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_union(
/*============*/
fts_query_t* query, /*!< in: query instance */
fts_string_t* token) /*!< in: token to search */
{
fts_fetch_t fetch;
ulint n_doc_ids = 0;
trx_t* trx = query->trx;
que_t* graph = NULL;
dberr_t error;
ut_a(query->oper == FTS_NONE || query->oper == FTS_DECR_RATING ||
query->oper == FTS_NEGATE || query->oper == FTS_INCR_RATING);
#ifdef FTS_INTERNAL_DIAG_PRINT
fprintf(stderr, "UNION: Searching: '%.*s'\n",
(int) token->f_len, token->f_str);
#endif
if (query->doc_ids) {
n_doc_ids = rbt_size(query->doc_ids);
}
if (token->f_len == 0) {
return(query->error);
}
/* Single '%' would confuse parser in pars_like_rebind(). In addition,
our wildcard search only supports prefix search */
ut_ad(*token->f_str != '%');
fts_query_cache(query, token);
/* Setup the callback args for filtering and
consolidating the ilist. */
fetch.read_arg = query;
fetch.read_record = fts_query_index_fetch_nodes;
/* Read the nodes from disk. */
error = fts_index_fetch_nodes(
trx, &graph, &query->fts_index_table, token, &fetch);
/* DB_FTS_EXCEED_RESULT_CACHE_LIMIT passed by 'query->error' */
ut_ad(!(query->error != DB_SUCCESS && error != DB_SUCCESS));
if (error != DB_SUCCESS) {
query->error = error;
}
fts_que_graph_free(graph);
if (query->error == DB_SUCCESS) {
/* The size can't decrease. */
ut_a(rbt_size(query->doc_ids) >= n_doc_ids);
/* Calulate the number of doc ids that were added to
the current doc id set. */
if (query->doc_ids) {
n_doc_ids = rbt_size(query->doc_ids) - n_doc_ids;
}
}
return(query->error);
}
/*****************************************************************//**
Depending upon the current query operator process the doc id.
return DB_SUCCESS if all go well
or return DB_FTS_EXCEED_RESULT_CACHE_LIMIT */
static
dberr_t
fts_query_process_doc_id(
/*=====================*/
fts_query_t* query, /*!< in: query instance */
doc_id_t doc_id, /*!< in: doc id to process */
fts_rank_t rank) /*!< in: if non-zero, it is the
rank associated with the doc_id */
{
if (query->flags == FTS_OPT_RANKING) {
return(DB_SUCCESS);
}
switch (query->oper) {
case FTS_NONE:
fts_query_union_doc_id(query, doc_id, rank);
break;
case FTS_EXIST:
fts_query_intersect_doc_id(query, doc_id, rank);
break;
case FTS_IGNORE:
fts_query_remove_doc_id(query, doc_id);
break;
case FTS_NEGATE:
fts_query_change_ranking(query, doc_id, TRUE);
break;
case FTS_DECR_RATING:
fts_query_union_doc_id(query, doc_id, rank);
fts_query_change_ranking(query, doc_id, TRUE);
break;
case FTS_INCR_RATING:
fts_query_union_doc_id(query, doc_id, rank);
fts_query_change_ranking(query, doc_id, FALSE);
break;
default:
ut_error;
}
if (query->total_size > fts_result_cache_limit) {
return(DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
} else {
return(DB_SUCCESS);
}
}
/*****************************************************************//**
Merge two result sets. */
static
dberr_t
fts_merge_doc_ids(
/*==============*/
fts_query_t* query, /*!< in,out: query instance */
const ib_rbt_t* doc_ids) /*!< in: result set to merge */
{
const ib_rbt_node_t* node;
DBUG_ENTER("fts_merge_doc_ids");
ut_a(!query->intersection);
/* To process FTS_EXIST operation (intersection), we need
to create a new result set for fts_query_intersect(). */
if (query->oper == FTS_EXIST) {
query->intersection = rbt_create(
sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
query->total_size += SIZEOF_RBT_CREATE;
}
/* Merge the elements to the result set. */
for (node = rbt_first(doc_ids); node; node = rbt_next(doc_ids, node)) {
fts_ranking_t* ranking;
ulint pos = 0;
fts_string_t word;
ranking = rbt_value(fts_ranking_t, node);
query->error = fts_query_process_doc_id(
query, ranking->doc_id, ranking->rank);
if (query->error != DB_SUCCESS) {
DBUG_RETURN(query->error);
}
/* Merge words. Don't need to take operator into account. */
ut_a(ranking->words);
while (fts_ranking_words_get_next(query, ranking, &pos, &word)) {
fts_query_add_word_to_document(query, ranking->doc_id,
&word);
}
}
/* If it is an intersection operation, reset query->doc_ids
to query->intersection and free the old result list. */
if (query->oper == FTS_EXIST && query->intersection != NULL) {
fts_query_free_doc_ids(query, query->doc_ids);
query->doc_ids = query->intersection;
query->intersection = NULL;
}
DBUG_RETURN(DB_SUCCESS);
}
/*****************************************************************//**
Skip non-whitespace in a string. Move ptr to the next word boundary.
@return pointer to first whitespace character or end */
UNIV_INLINE
byte*
fts_query_skip_word(
/*================*/
byte* ptr, /*!< in: start of scan */
const byte* end) /*!< in: pointer to end of string */
{
/* TODO: Does this have to be UTF-8 too ? */
while (ptr < end && !(ispunct(*ptr) || isspace(*ptr))) {
++ptr;
}
return(ptr);
}
/*****************************************************************//**
Check whether the remaining terms in the phrase match the text.
@return TRUE if matched else FALSE */
static
ibool
fts_query_match_phrase_terms(
/*=========================*/
fts_phrase_t* phrase, /*!< in: phrase to match */
byte** start, /*!< in/out: text to search, we can't
make this const becase we need to
first convert the string to
lowercase */
const byte* end, /*!< in: pointer to the end of
the string to search */
mem_heap_t* heap) /*!< in: heap */
{
ulint i;
byte* ptr = *start;
const ib_vector_t* tokens = phrase->tokens;
ulint distance = phrase->distance;
/* We check only from the second term onwards, since the first
must have matched otherwise we wouldn't be here. */
for (i = 1; ptr < end && i < ib_vector_size(tokens); /* No op */) {
fts_string_t match;
fts_string_t cmp_str;
const fts_string_t* token;
int result;
ulint ret;
ulint offset;
ret = innobase_mysql_fts_get_token(
phrase->charset, ptr, (byte*) end,
&match, &offset);
if (match.f_len > 0) {
/* Get next token to match. */
token = static_cast<const fts_string_t*>(
ib_vector_get_const(tokens, i));
fts_utf8_string_dup(&cmp_str, &match, heap);
result = innobase_fts_text_case_cmp(
phrase->charset, token, &cmp_str);
/* Skip the rest of the tokens if this one doesn't
match and the proximity distance is exceeded. */
if (result
&& (distance == ULINT_UNDEFINED
|| distance == 0)) {
break;
}
/* This token matched move to the next token. */
if (result == 0) {
/* Advance the text to search by the length
of the last token. */
ptr += ret;
/* Advance to the next token. */
++i;
} else {
ut_a(distance != ULINT_UNDEFINED);
ptr = fts_query_skip_word(ptr, end);
}
/* Distance can be 0 for exact matches. */
if (distance != ULINT_UNDEFINED && distance > 0) {
--distance;
}
} else {
ptr += ret;
}
}
*start = ptr;
/* Can't be greater than the number of elements. */
ut_a(i <= ib_vector_size(tokens));
/* This is the case for multiple words. */
if (i == ib_vector_size(tokens)) {
phrase->found = TRUE;
}
return(phrase->found);
}
/*****************************************************************//**
Callback function to count the number of words in position ranges,
and see whether the word count is in specified "phrase->distance"
@return true if the number of characters is less than the "distance" */
static
bool
fts_proximity_is_word_in_range(
/*===========================*/
const fts_phrase_t*
phrase, /*!< in: phrase with the search info */
byte* start, /*!< in: text to search */
ulint total_len) /*!< in: length of text */
{
fts_proximity_t* proximity_pos = phrase->proximity_pos;
ut_ad(proximity_pos->n_pos == proximity_pos->min_pos.size());
ut_ad(proximity_pos->n_pos == proximity_pos->max_pos.size());
/* Search each matched position pair (with min and max positions)
and count the number of words in the range */
for (ulint i = 0; i < proximity_pos->n_pos; i++) {
ulint cur_pos = proximity_pos->min_pos[i];
ulint n_word = 0;
ut_ad(proximity_pos->max_pos[i] <= total_len);
/* Walk through words in the range and count them */
while (cur_pos <= proximity_pos->max_pos[i]) {
ulint len;
fts_string_t str;
ulint offset = 0;
len = innobase_mysql_fts_get_token(
phrase->charset,
start + cur_pos,
start + total_len, &str, &offset);
if (len == 0) {
break;
}
/* Advances position with "len" bytes */
cur_pos += len;
/* Record the number of words */
if (str.f_n_char > 0) {
n_word++;
}
if (n_word > phrase->distance) {
break;
}
}
/* Check if the number of words is less than specified
"distance" */
if (n_word && n_word <= phrase->distance) {
return(true);
}
}
return(false);
}
/*****************************************************************//**
Callback function to fetch and search the document.
@return TRUE if matched else FALSE */
static
ibool
fts_query_match_phrase(
/*===================*/
fts_phrase_t* phrase, /*!< in: phrase to match */
byte* start, /*!< in: text to search, we can't make
this const becase we need to first
convert the string to lowercase */
ulint cur_len, /*!< in: length of text */
ulint prev_len, /*!< in: total length for searched
doc fields*/
mem_heap_t* heap) /* heap */
{
ulint i;
const fts_string_t* first;
const byte* end = start + cur_len;
const ib_vector_t* tokens = phrase->tokens;
const ib_vector_t* positions = phrase->match->positions;
ut_a(!phrase->found);
ut_a(phrase->match->doc_id > 0);
ut_a(ib_vector_size(tokens) > 0);
ut_a(ib_vector_size(positions) > 0);
first = static_cast<const fts_string_t*>(
ib_vector_get_const(tokens, 0));
ut_a(phrase->match->start < ib_vector_size(positions));
for (i = phrase->match->start; i < ib_vector_size(positions); ++i) {
ulint pos;
fts_string_t match;
fts_string_t cmp_str;
byte* ptr = start;
ulint ret;
ulint offset;
pos = *(ulint*) ib_vector_get_const(positions, i);
if (pos == ULINT_UNDEFINED) {
break;
}
if (pos < prev_len) {
continue;
}
/* Document positions are calculated from the beginning
of the first field, need to save the length for each
searched field to adjust the doc position when search
phrases. */
pos -= prev_len;
ptr = match.f_str = start + pos;
/* Within limits ? */
if (ptr >= end) {
break;
}
ret = innobase_mysql_fts_get_token(
phrase->charset, start + pos, (byte*) end,
&match, &offset);
if (match.f_len == 0) {
break;
}
fts_utf8_string_dup(&cmp_str, &match, heap);
if (innobase_fts_text_case_cmp(
phrase->charset, first, &cmp_str) == 0) {
/* This is the case for the single word
in the phrase. */
if (ib_vector_size(phrase->tokens) == 1) {
phrase->found = TRUE;
break;
}
ptr += ret;
/* Match the remaining terms in the phrase. */
if (fts_query_match_phrase_terms(phrase, &ptr,
end, heap)) {
break;
}
}
}
return(phrase->found);
}
/*****************************************************************//**
Callback function to fetch and search the document.
@return whether the phrase is found */
static
ibool
fts_query_fetch_document(
/*=====================*/
void* row, /*!< in: sel_node_t* */
void* user_arg) /*!< in: fts_doc_t* */
{
que_node_t* exp;
sel_node_t* node = static_cast<sel_node_t*>(row);
fts_phrase_t* phrase = static_cast<fts_phrase_t*>(user_arg);
ulint prev_len = 0;
ulint total_len = 0;
byte* document_text = NULL;
exp = node->select_list;
phrase->found = FALSE;
/* For proximity search, we will need to get the whole document
from all fields, so first count the total length of the document
from all the fields */
if (phrase->proximity_pos) {
while (exp) {
ulint field_len;
dfield_t* dfield = que_node_get_val(exp);
byte* data = static_cast<byte*>(
dfield_get_data(dfield));
if (dfield_is_ext(dfield)) {
ulint local_len = dfield_get_len(dfield);
local_len -= BTR_EXTERN_FIELD_REF_SIZE;
field_len = mach_read_from_4(
data + local_len + BTR_EXTERN_LEN + 4);
} else {
field_len = dfield_get_len(dfield);
}
if (field_len != UNIV_SQL_NULL) {
total_len += field_len + 1;
}
exp = que_node_get_next(exp);
}
document_text = static_cast<byte*>(mem_heap_zalloc(
phrase->heap, total_len));
if (!document_text) {
return(FALSE);
}
}
exp = node->select_list;
while (exp) {
dfield_t* dfield = que_node_get_val(exp);
byte* data = static_cast<byte*>(
dfield_get_data(dfield));
ulint cur_len;
if (dfield_is_ext(dfield)) {
data = btr_copy_externally_stored_field(
&cur_len, data, phrase->zip_size,
dfield_get_len(dfield), phrase->heap);
} else {
cur_len = dfield_get_len(dfield);
}
if (cur_len != UNIV_SQL_NULL && cur_len != 0) {
if (phrase->proximity_pos) {
ut_ad(prev_len + cur_len <= total_len);
memcpy(document_text + prev_len, data, cur_len);
} else {
/* For phrase search */
phrase->found =
fts_query_match_phrase(
phrase,
static_cast<byte*>(data),
cur_len, prev_len,
phrase->heap);
}
/* Document positions are calculated from the beginning
of the first field, need to save the length for each
searched field to adjust the doc position when search
phrases. */
prev_len += cur_len + 1;
}
if (phrase->found) {
break;
}
exp = que_node_get_next(exp);
}
if (phrase->proximity_pos) {
ut_ad(prev_len <= total_len);
phrase->found = fts_proximity_is_word_in_range(
phrase, document_text, total_len);
}
return(phrase->found);
}
#if 0
/********************************************************************
Callback function to check whether a record was found or not. */
static
ibool
fts_query_select(
/*=============*/
void* row, /*!< in: sel_node_t* */
void* user_arg) /*!< in: fts_doc_t* */
{
int i;
que_node_t* exp;
sel_node_t* node = row;
fts_select_t* select = user_arg;
ut_a(select->word_freq);
ut_a(select->word_freq->doc_freqs);
exp = node->select_list;
for (i = 0; exp && !select->found; ++i) {
dfield_t* dfield = que_node_get_val(exp);
void* data = dfield_get_data(dfield);
ulint len = dfield_get_len(dfield);
switch (i) {
case 0: /* DOC_COUNT */
if (len != UNIV_SQL_NULL && len != 0) {
select->word_freq->doc_count +=
mach_read_from_4(data);
}
break;
case 1: /* ILIST */
if (len != UNIV_SQL_NULL && len != 0) {
fts_query_find_doc_id(select, data, len);
}
break;
default:
ut_error;
}
exp = que_node_get_next(exp);
}
return(FALSE);
}
/********************************************************************
Read the rows from the FTS index, that match word and where the
doc id is between first and last doc id.
@return DB_SUCCESS if all go well else error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_find_term(
/*================*/
fts_query_t* query, /*!< in: FTS query state */
que_t** graph, /*!< in: prepared statement */
const fts_string_t* word, /*!< in: the word to fetch */
doc_id_t doc_id, /*!< in: doc id to match */
ulint* min_pos,/*!< in/out: pos found must be
greater than this minimum value. */
ibool* found) /*!< out: TRUE if found else FALSE */
{
pars_info_t* info;
dberr_t error;
fts_select_t select;
doc_id_t match_doc_id;
trx_t* trx = query->trx;
trx->op_info = "fetching FTS index matching nodes";
if (*graph) {
info = (*graph)->info;
} else {
info = pars_info_create();
}
select.found = FALSE;
select.doc_id = doc_id;
select.min_pos = *min_pos;
select.word_freq = fts_query_add_word_freq(query, word->f_str);
pars_info_bind_function(info, "my_func", fts_query_select, &select);
pars_info_bind_varchar_literal(info, "word", word->f_str, word->f_len);
/* Convert to "storage" byte order. */
fts_write_doc_id((byte*) &match_doc_id, doc_id);
fts_bind_doc_id(info, "min_doc_id", &match_doc_id);
fts_bind_doc_id(info, "max_doc_id", &match_doc_id);
if (!*graph) {
ulint selected;
selected = fts_select_index(*word->f_str);
query->fts_index_table.suffix = fts_get_suffix(selected);
*graph = fts_parse_sql(
&query->fts_index_table,
info,
"DECLARE FUNCTION my_func;\n"
"DECLARE CURSOR c IS"
" SELECT doc_count, ilist\n"
" FROM \"%s\"\n"
" WHERE word LIKE :word AND "
" first_doc_id <= :min_doc_id AND "
" last_doc_id >= :max_doc_id\n"
" ORDER BY first_doc_id;\n"
"BEGIN\n"
"\n"
"OPEN c;\n"
"WHILE 1 = 1 LOOP\n"
" FETCH c INTO my_func();\n"
" IF c % NOTFOUND THEN\n"
" EXIT;\n"
" END IF;\n"
"END LOOP;\n"
"CLOSE c;");
}
for(;;) {
error = fts_eval_sql(trx, *graph);
if (error == DB_SUCCESS) {
break; /* Exit the loop. */
} else {
ut_print_timestamp(stderr);
if (error == DB_LOCK_WAIT_TIMEOUT) {
fprintf(stderr, " InnoDB: Warning: lock wait "
"timeout reading FTS index. "
"Retrying!\n");
trx->error_state = DB_SUCCESS;
} else {
fprintf(stderr, " InnoDB: Error: %lu "
"while reading FTS index.\n", error);
break; /* Exit the loop. */
}
}
}
/* Value to return */
*found = select.found;
if (*found) {
*min_pos = select.min_pos;
}
return(error);
}
/********************************************************************
Callback aggregator for int columns. */
static
ibool
fts_query_sum(
/*==========*/
/*!< out: always returns TRUE */
void* row, /*!< in: sel_node_t* */
void* user_arg) /*!< in: ulint* */
{
que_node_t* exp;
sel_node_t* node = row;
ulint* total = user_arg;
exp = node->select_list;
while (exp) {
dfield_t* dfield = que_node_get_val(exp);
void* data = dfield_get_data(dfield);
ulint len = dfield_get_len(dfield);
if (len != UNIV_SQL_NULL && len != 0) {
*total += mach_read_from_4(data);
}
exp = que_node_get_next(exp);
}
return(TRUE);
}
/********************************************************************
Calculate the total documents that contain a particular word (term).
@return DB_SUCCESS if all go well else error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_total_docs_containing_term(
/*=================================*/
fts_query_t* query, /*!< in: FTS query state */
const fts_string_t* word, /*!< in: the word to check */
ulint* total) /*!< out: documents containing word */
{
pars_info_t* info;
dberr_t error;
que_t* graph;
ulint selected;
trx_t* trx = query->trx;
trx->op_info = "fetching FTS index document count";
*total = 0;
info = pars_info_create();
pars_info_bind_function(info, "my_func", fts_query_sum, total);
pars_info_bind_varchar_literal(info, "word", word->f_str, word->f_len);
selected = fts_select_index(*word->f_str);
query->fts_index_table.suffix = fts_get_suffix(selected);
graph = fts_parse_sql(
&query->fts_index_table,
info,
"DECLARE FUNCTION my_func;\n"
"DECLARE CURSOR c IS"
" SELECT doc_count\n"
" FROM %s\n"
" WHERE word = :word "
" ORDER BY first_doc_id;\n"
"BEGIN\n"
"\n"
"OPEN c;\n"
"WHILE 1 = 1 LOOP\n"
" FETCH c INTO my_func();\n"
" IF c % NOTFOUND THEN\n"
" EXIT;\n"
" END IF;\n"
"END LOOP;\n"
"CLOSE c;");
for(;;) {
error = fts_eval_sql(trx, graph);
if (error == DB_SUCCESS) {
break; /* Exit the loop. */
} else {
ut_print_timestamp(stderr);
if (error == DB_LOCK_WAIT_TIMEOUT) {
fprintf(stderr, " InnoDB: Warning: lock wait "
"timeout reading FTS index. "
"Retrying!\n");
trx->error_state = DB_SUCCESS;
} else {
fprintf(stderr, " InnoDB: Error: %lu "
"while reading FTS index.\n", error);
break; /* Exit the loop. */
}
}
}
fts_que_graph_free(graph);
return(error);
}
/********************************************************************
Get the total number of words in a documents.
@return DB_SUCCESS if all go well else error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_terms_in_document(
/*========================*/
fts_query_t* query, /*!< in: FTS query state */
doc_id_t doc_id, /*!< in: the word to check */
ulint* total) /*!< out: total words in document */
{
pars_info_t* info;
dberr_t error;
que_t* graph;
doc_id_t read_doc_id;
trx_t* trx = query->trx;
trx->op_info = "fetching FTS document term count";
*total = 0;
info = pars_info_create();
pars_info_bind_function(info, "my_func", fts_query_sum, total);
/* Convert to "storage" byte order. */
fts_write_doc_id((byte*) &read_doc_id, doc_id);
fts_bind_doc_id(info, "doc_id", &read_doc_id);
query->fts_index_table.suffix = "DOC_ID";
graph = fts_parse_sql(
&query->fts_index_table,
info,
"DECLARE FUNCTION my_func;\n"
"DECLARE CURSOR c IS"
" SELECT count\n"
" FROM \"%s\"\n"
" WHERE doc_id = :doc_id "
"BEGIN\n"
"\n"
"OPEN c;\n"
"WHILE 1 = 1 LOOP\n"
" FETCH c INTO my_func();\n"
" IF c % NOTFOUND THEN\n"
" EXIT;\n"
" END IF;\n"
"END LOOP;\n"
"CLOSE c;");
for(;;) {
error = fts_eval_sql(trx, graph);
if (error == DB_SUCCESS) {
break; /* Exit the loop. */
} else {
ut_print_timestamp(stderr);
if (error == DB_LOCK_WAIT_TIMEOUT) {
fprintf(stderr, " InnoDB: Warning: lock wait "
"timeout reading FTS doc id table. "
"Retrying!\n");
trx->error_state = DB_SUCCESS;
} else {
fprintf(stderr, " InnoDB: Error: %lu "
"while reading FTS doc id table.\n",
error);
break; /* Exit the loop. */
}
}
}
fts_que_graph_free(graph);
return(error);
}
#endif
/*****************************************************************//**
Retrieve the document and match the phrase tokens.
@return DB_SUCCESS or error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_match_document(
/*=====================*/
ib_vector_t* tokens, /*!< in: phrase tokens */
fts_get_doc_t* get_doc, /*!< in: table and prepared statements */
fts_match_t* match, /*!< in: doc id and positions */
ulint distance, /*!< in: proximity distance */
ibool* found) /*!< out: TRUE if phrase found */
{
dberr_t error;
fts_phrase_t phrase;
memset(&phrase, 0x0, sizeof(phrase));
phrase.match = match; /* Positions to match */
phrase.tokens = tokens; /* Tokens to match */
phrase.distance = distance;
phrase.charset = get_doc->index_cache->charset;
phrase.zip_size = dict_table_zip_size(
get_doc->index_cache->index->table);
phrase.heap = mem_heap_create(512);
*found = phrase.found = FALSE;
error = fts_doc_fetch_by_doc_id(
get_doc, match->doc_id, NULL, FTS_FETCH_DOC_BY_ID_EQUAL,
fts_query_fetch_document, &phrase);
if (error != DB_SUCCESS) {
ut_print_timestamp(stderr);
fprintf(stderr, "InnoDB: Error: (%s) matching document.\n",
ut_strerr(error));
} else {
*found = phrase.found;
}
mem_heap_free(phrase.heap);
return(error);
}
/*****************************************************************//**
This function fetches the original documents and count the
words in between matching words to see that is in specified distance
@return DB_SUCCESS if all OK */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
bool
fts_query_is_in_proximity_range(
/*============================*/
const fts_query_t* query, /*!< in: query instance */
fts_match_t** match, /*!< in: query instance */
fts_proximity_t* qualified_pos) /*!< in: position info for
qualified ranges */
{
fts_get_doc_t get_doc;
fts_cache_t* cache = query->index->table->fts->cache;
dberr_t err;
fts_phrase_t phrase;
memset(&get_doc, 0x0, sizeof(get_doc));
memset(&phrase, 0x0, sizeof(phrase));
rw_lock_x_lock(&cache->lock);
get_doc.index_cache = fts_find_index_cache(cache, query->index);
rw_lock_x_unlock(&cache->lock);
ut_a(get_doc.index_cache != NULL);
phrase.distance = query->distance;
phrase.charset = get_doc.index_cache->charset;
phrase.zip_size = dict_table_zip_size(
get_doc.index_cache->index->table);
phrase.heap = mem_heap_create(512);
phrase.proximity_pos = qualified_pos;
phrase.found = FALSE;
err = fts_doc_fetch_by_doc_id(
&get_doc, match[0]->doc_id, NULL, FTS_FETCH_DOC_BY_ID_EQUAL,
fts_query_fetch_document, &phrase);
if (err != DB_SUCCESS) {
ib_logf(IB_LOG_LEVEL_ERROR,
"Error: (%s) in verification phase of proximity "
"search", ut_strerr(err));
}
/* Free the prepared statement. */
if (get_doc.get_document_graph) {
fts_que_graph_free(get_doc.get_document_graph);
get_doc.get_document_graph = NULL;
}
mem_heap_free(phrase.heap);
return(err == DB_SUCCESS && phrase.found);
}
/*****************************************************************//**
Iterate over the matched document ids and search the for the
actual phrase in the text.
@return DB_SUCCESS if all OK */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_search_phrase(
/*====================*/
fts_query_t* query, /*!< in: query instance */
ib_vector_t* orig_tokens, /*!< in: tokens to search,
with any stopwords in the
original phrase */
ib_vector_t* tokens) /*!< in: tokens that does
not include stopwords and
can be used to calculate
ranking */
{
ulint i;
fts_get_doc_t get_doc;
ulint n_matched;
fts_cache_t* cache = query->index->table->fts->cache;
n_matched = ib_vector_size(query->matched);
/* Setup the doc retrieval infrastructure. */
memset(&get_doc, 0x0, sizeof(get_doc));
rw_lock_x_lock(&cache->lock);
get_doc.index_cache = fts_find_index_cache(cache, query->index);
/* Must find the index cache */
ut_a(get_doc.index_cache != NULL);
rw_lock_x_unlock(&cache->lock);
#ifdef FTS_INTERNAL_DIAG_PRINT
ut_print_timestamp(stderr);
fprintf(stderr, " Start phrase search\n");
#endif
/* Read the document from disk and do the actual
match, matching documents will be added to the current
doc id set. */
for (i = 0; i < n_matched && query->error == DB_SUCCESS; ++i) {
fts_match_t* match;
ibool found = FALSE;
match = static_cast<fts_match_t*>(
ib_vector_get(query->matched, i));
/* Skip the document ids that were filtered out by
an earlier pass. */
if (match->doc_id != 0) {
query->error = fts_query_match_document(
orig_tokens, &get_doc,
match, query->distance, &found);
if (query->error == DB_SUCCESS && found) {
ulint z;
query->error = fts_query_process_doc_id(query,
match->doc_id, 0);
if (query->error != DB_SUCCESS) {
goto func_exit;
}
for (z = 0; z < ib_vector_size(tokens); z++) {
fts_string_t* token;
token = static_cast<fts_string_t*>(
ib_vector_get(tokens, z));
fts_query_add_word_to_document(
query, match->doc_id, token);
}
}
}
}
func_exit:
/* Free the prepared statement. */
if (get_doc.get_document_graph) {
fts_que_graph_free(get_doc.get_document_graph);
get_doc.get_document_graph = NULL;
}
return(query->error);
}
/*****************************************************************//**
Text/Phrase search.
@return DB_SUCCESS or error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_phrase_search(
/*====================*/
fts_query_t* query, /*!< in: query instance */
const fts_string_t* phrase) /*!< in: token to search */
{
ib_vector_t* tokens;
ib_vector_t* orig_tokens;
mem_heap_t* heap = mem_heap_create(sizeof(fts_string_t));
ulint len = phrase->f_len;
ulint cur_pos = 0;
ib_alloc_t* heap_alloc;
ulint num_token;
CHARSET_INFO* charset;
charset = query->fts_index_table.charset;
heap_alloc = ib_heap_allocator_create(heap);
tokens = ib_vector_create(heap_alloc, sizeof(fts_string_t), 4);
orig_tokens = ib_vector_create(heap_alloc, sizeof(fts_string_t), 4);
if (query->distance != ULINT_UNDEFINED && query->distance > 0) {
query->flags = FTS_PROXIMITY;
} else {
query->flags = FTS_PHRASE;
}
/* Split the phrase into tokens. */
while (cur_pos < len) {
fts_cache_t* cache = query->index->table->fts->cache;
ib_rbt_bound_t parent;
ulint offset;
ulint cur_len;
fts_string_t result_str;
cur_len = innobase_mysql_fts_get_token(
charset,
reinterpret_cast<const byte*>(phrase->f_str) + cur_pos,
reinterpret_cast<const byte*>(phrase->f_str) + len,
&result_str, &offset);
if (cur_len == 0) {
break;
}
cur_pos += cur_len;
if (result_str.f_n_char == 0) {
continue;
}
fts_string_t* token = static_cast<fts_string_t*>(
ib_vector_push(tokens, NULL));
token->f_str = static_cast<byte*>(
mem_heap_alloc(heap, result_str.f_len + 1));
ut_memcpy(token->f_str, result_str.f_str, result_str.f_len);
token->f_len = result_str.f_len;
token->f_str[token->f_len] = 0;
if (cache->stopword_info.cached_stopword
&& rbt_search(cache->stopword_info.cached_stopword,
&parent, token) != 0
&& result_str.f_n_char >= fts_min_token_size
&& result_str.f_n_char <= fts_max_token_size) {
/* Add the word to the RB tree so that we can
calculate it's frequencey within a document. */
fts_query_add_word_freq(query, token);
} else {
ib_vector_pop(tokens);
}
/* we will start to store all words including stopwords
in the "orig_tokens" vector, but skip any leading words
that are stopwords */
if (!ib_vector_is_empty(tokens)) {
fts_string_t* orig_token = static_cast<fts_string_t*>(
ib_vector_push(orig_tokens, NULL));
orig_token->f_str = token->f_str;
orig_token->f_len = token->f_len;
}
}
num_token = ib_vector_size(tokens);
if (num_token > MAX_PROXIMITY_ITEM) {
query->error = DB_FTS_TOO_MANY_WORDS_IN_PHRASE;
goto func_exit;
}
ut_ad(ib_vector_size(orig_tokens) >= num_token);
/* Ignore empty strings. */
if (num_token > 0) {
fts_string_t* token;
fts_fetch_t fetch;
trx_t* trx = query->trx;
fts_ast_oper_t oper = query->oper;
que_t* graph = NULL;
ulint i;
dberr_t error;
/* Create the vector for storing matching document ids
and the positions of the first token of the phrase. */
if (!query->matched) {
ib_alloc_t* heap_alloc;
heap_alloc = ib_heap_allocator_create(heap);
if (!(query->flags & FTS_PROXIMITY)
&& !(query->flags & FTS_PHRASE)) {
query->matched = ib_vector_create(
heap_alloc, sizeof(fts_match_t),
64);
} else {
ut_a(num_token <= MAX_PROXIMITY_ITEM);
query->match_array =
(ib_vector_t**) mem_heap_alloc(
heap,
num_token *
sizeof(query->matched));
for (i = 0; i < num_token; i++) {
query->match_array[i] =
ib_vector_create(
heap_alloc, sizeof(fts_match_t),
64);
}
query->matched = query->match_array[0];
}
}
/* Setup the callback args for filtering and consolidating
the ilist. */
fetch.read_arg = query;
fetch.read_record = fts_query_index_fetch_nodes;
for (i = 0; i < num_token; i++) {
/* Search for the first word from the phrase. */
token = static_cast<fts_string_t*>(
ib_vector_get(tokens, i));
if (query->flags & FTS_PROXIMITY
|| query->flags & FTS_PHRASE) {
query->matched = query->match_array[i];
}
error = fts_index_fetch_nodes(
trx, &graph, &query->fts_index_table,
token, &fetch);
/* DB_FTS_EXCEED_RESULT_CACHE_LIMIT passed by 'query->error' */
ut_ad(!(query->error != DB_SUCCESS && error != DB_SUCCESS));
if (error != DB_SUCCESS) {
query->error = error;
}
fts_que_graph_free(graph);
graph = NULL;
fts_query_cache(query, token);
if (!(query->flags & FTS_PHRASE)
&& !(query->flags & FTS_PROXIMITY)) {
break;
}
/* If any of the token can't be found,
no need to continue match */
if (ib_vector_is_empty(query->match_array[i])
|| query->error != DB_SUCCESS) {
goto func_exit;
}
}
/* Just a single word, no need to fetch the original
documents to do phrase matching */
if (ib_vector_size(orig_tokens) == 1
&& !ib_vector_is_empty(query->match_array[0])) {
fts_match_t* match;
ulint n_matched;
n_matched = ib_vector_size(query->match_array[0]);
for (i = 0; i < n_matched; i++) {
match = static_cast<fts_match_t*>(
ib_vector_get(
query->match_array[0], i));
query->error = fts_query_process_doc_id(
query, match->doc_id, 0);
if (query->error != DB_SUCCESS) {
goto func_exit;
}
fts_query_add_word_to_document(
query, match->doc_id, token);
}
query->oper = oper;
goto func_exit;
}
/* If we are doing proximity search, verify the distance
between all words, and check they are in specified distance. */
if (query->flags & FTS_PROXIMITY) {
fts_phrase_or_proximity_search(query, tokens);
} else {
ibool matched;
/* Phrase Search case:
We filter out the doc ids that don't contain
all the tokens in the phrase. It's cheaper to
search the ilist than bringing the documents in
and then doing a search through the text. Isolated
testing shows this also helps in mitigating disruption
of the buffer cache. */
matched = fts_phrase_or_proximity_search(query, tokens);
query->matched = query->match_array[0];
/* Read the actual text in and search for the phrase. */
if (matched) {
ut_ad(query->error == DB_SUCCESS);
query->error = fts_query_search_phrase(
query, orig_tokens, tokens);
}
}
/* Restore original operation. */
query->oper = oper;
if (query->error != DB_SUCCESS) {
goto func_exit;
}
}
func_exit:
mem_heap_free(heap);
/* Don't need it anymore. */
query->matched = NULL;
return(query->error);
}
/*****************************************************************//**
Find the word and evaluate.
@return DB_SUCCESS if all go well */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_query_execute(
/*==============*/
fts_query_t* query, /*!< in: query instance */
fts_string_t* token) /*!< in: token to search */
{
switch (query->oper) {
case FTS_NONE:
case FTS_NEGATE:
case FTS_INCR_RATING:
case FTS_DECR_RATING:
query->error = fts_query_union(query, token);
break;
case FTS_EXIST:
query->error = fts_query_intersect(query, token);
break;
case FTS_IGNORE:
query->error = fts_query_difference(query, token);
break;
default:
ut_error;
}
return(query->error);
}
/*****************************************************************//**
Create a wildcard string. It's the responsibility of the caller to
free the byte* pointer. It's allocated using ut_malloc().
@return ptr to allocated memory */
static
byte*
fts_query_get_token(
/*================*/
fts_ast_node_t* node, /*!< in: the current sub tree */
fts_string_t* token) /*!< in: token to create */
{
ulint str_len;
byte* new_ptr = NULL;
str_len = node->term.ptr->len;
ut_a(node->type == FTS_AST_TERM);
token->f_len = str_len;
token->f_str = node->term.ptr->str;
if (node->term.wildcard) {
token->f_str = static_cast<byte*>(ut_malloc(str_len + 2));
token->f_len = str_len + 1;
memcpy(token->f_str, node->term.ptr->str, str_len);
token->f_str[str_len] = '%';
token->f_str[token->f_len] = 0;
new_ptr = token->f_str;
}
return(new_ptr);
}
/*****************************************************************//**
Visit every node of the AST. */
static
dberr_t
fts_query_visitor(
/*==============*/
fts_ast_oper_t oper, /*!< in: current operator */
fts_ast_node_t* node, /*!< in: The root of the current subtree*/
void* arg) /*!< in: callback arg*/
{
byte* ptr;
fts_string_t token;
fts_query_t* query = static_cast<fts_query_t*>(arg);
ut_a(node);
DBUG_ENTER("fts_query_visitor");
DBUG_PRINT("fts", ("nodetype: %s", fts_ast_node_type_get(node->type)));
token.f_n_char = 0;
query->oper = oper;
query->cur_node = node;
switch (node->type) {
case FTS_AST_TEXT:
token.f_str = node->text.ptr->str;
token.f_len = node->text.ptr->len;
if (query->oper == FTS_EXIST) {
ut_ad(query->intersection == NULL);
query->intersection = rbt_create(
sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
query->total_size += SIZEOF_RBT_CREATE;
}
/* Set the current proximity distance. */
query->distance = node->text.distance;
/* Force collection of doc ids and the positions. */
query->collect_positions = TRUE;
query->error = fts_query_phrase_search(query, &token);
query->collect_positions = FALSE;
if (query->oper == FTS_EXIST) {
fts_query_free_doc_ids(query, query->doc_ids);
query->doc_ids = query->intersection;
query->intersection = NULL;
}
break;
case FTS_AST_TERM:
token.f_str = node->term.ptr->str;
token.f_len = node->term.ptr->len;
/* Add the word to our RB tree that will be used to
calculate this terms per document frequency. */
fts_query_add_word_freq(query, &token);
ptr = fts_query_get_token(node, &token);
query->error = fts_query_execute(query, &token);
if (ptr) {
ut_free(ptr);
}
break;
case FTS_AST_SUBEXP_LIST:
query->error = fts_ast_visit_sub_exp(node, fts_query_visitor, arg);
break;
default:
ut_error;
}
if (query->oper == FTS_EXIST) {
query->multi_exist = true;
}
DBUG_RETURN(query->error);
}
/*****************************************************************//**
Process (nested) sub-expression, create a new result set to store the
sub-expression result by processing nodes under current sub-expression
list. Merge the sub-expression result with that of parent expression list.
@return DB_SUCCESS if all well */
UNIV_INTERN
dberr_t
fts_ast_visit_sub_exp(
/*==================*/
fts_ast_node_t* node, /*!< in,out: current root node */
fts_ast_callback visitor, /*!< in: callback function */
void* arg) /*!< in,out: arg for callback */
{
fts_ast_oper_t cur_oper;
fts_query_t* query = static_cast<fts_query_t*>(arg);
ib_rbt_t* parent_doc_ids;
ib_rbt_t* subexpr_doc_ids;
dberr_t error = DB_SUCCESS;
bool will_be_ignored = false;
bool multi_exist;
DBUG_ENTER("fts_ast_visit_sub_exp");
ut_a(node->type == FTS_AST_SUBEXP_LIST);
cur_oper = query->oper;
/* Save current result set */
parent_doc_ids = query->doc_ids;
/* Create new result set to store the sub-expression result. We
will merge this result set with the parent after processing. */
query->doc_ids = rbt_create(sizeof(fts_ranking_t),
fts_ranking_doc_id_cmp);
query->total_size += SIZEOF_RBT_CREATE;
multi_exist = query->multi_exist;
query->multi_exist = false;
/* Process nodes in current sub-expression and store its
result set in query->doc_ids we created above. */
error = fts_ast_visit(FTS_NONE, node, visitor,
arg, &will_be_ignored);
/* Reinstate parent node state */
query->multi_exist = multi_exist;
query->oper = cur_oper;
/* Merge the sub-expression result with the parent result set. */
subexpr_doc_ids = query->doc_ids;
query->doc_ids = parent_doc_ids;
if (error == DB_SUCCESS) {
error = fts_merge_doc_ids(query, subexpr_doc_ids);
}
/* Free current result set. Result already merged into parent. */
fts_query_free_doc_ids(query, subexpr_doc_ids);
DBUG_RETURN(error);
}
#if 0
/*****************************************************************//***
Check if the doc id exists in the ilist.
@return TRUE if doc id found */
static
ulint
fts_query_find_doc_id(
/*==================*/
fts_select_t* select, /*!< in/out: contains the doc id to
find, we update the word freq if
document found */
void* data, /*!< in: doc id ilist */
ulint len) /*!< in: doc id ilist size */
{
byte* ptr = data;
doc_id_t doc_id = 0;
ulint decoded = 0;
/* Decode the ilist and search for selected doc_id. We also
calculate the frequency of the word in the document if found. */
while (decoded < len && !select->found) {
ulint freq = 0;
ulint min_pos = 0;
ulint last_pos = 0;
ulint pos = fts_decode_vlc(&ptr);
/* Add the delta. */
doc_id += pos;
while (*ptr) {
++freq;
last_pos += fts_decode_vlc(&ptr);
/* Only if min_pos is not set and the current
term exists in a position greater than the
min_pos of the previous term. */
if (min_pos == 0 && last_pos > select->min_pos) {
min_pos = last_pos;
}
}
/* Skip the end of word position marker. */
++ptr;
/* Bytes decoded so far. */
decoded = ptr - (byte*) data;
/* A word may exist in the document but we only consider a
match if it exists in a position that is greater than the
position of the previous term. */
if (doc_id == select->doc_id && min_pos > 0) {
fts_doc_freq_t* doc_freq;
/* Add the doc id to the doc freq rb tree, if
the doc id doesn't exist it will be created. */
doc_freq = fts_query_add_doc_freq(
select->word_freq->doc_freqs, doc_id);
/* Avoid duplicating the frequency tally */
if (doc_freq->freq == 0) {
doc_freq->freq = freq;
}
select->found = TRUE;
select->min_pos = min_pos;
}
}
return(select->found);
}
#endif
/*****************************************************************//**
Read and filter nodes.
@return DB_SUCCESS if all go well,
or return DB_FTS_EXCEED_RESULT_CACHE_LIMIT */
static
dberr_t
fts_query_filter_doc_ids(
/*=====================*/
fts_query_t* query, /*!< in: query instance */
const fts_string_t* word, /*!< in: the current word */
fts_word_freq_t* word_freq, /*!< in/out: word frequency */
const fts_node_t* node, /*!< in: current FTS node */
void* data, /*!< in: doc id ilist */
ulint len, /*!< in: doc id ilist size */
ibool calc_doc_count) /*!< in: whether to remember doc count */
{
byte* ptr = static_cast<byte*>(data);
doc_id_t doc_id = 0;
ulint decoded = 0;
ib_rbt_t* doc_freqs = word_freq->doc_freqs;
/* Decode the ilist and add the doc ids to the query doc_id set. */
while (decoded < len) {
ulint freq = 0;
fts_doc_freq_t* doc_freq;
fts_match_t* match = NULL;
ulint last_pos = 0;
ulint pos = fts_decode_vlc(&ptr);
/* Some sanity checks. */
if (doc_id == 0) {
ut_a(pos == node->first_doc_id);
}
/* Add the delta. */
doc_id += pos;
if (calc_doc_count) {
word_freq->doc_count++;
}
/* We simply collect the matching instances here. */
if (query->collect_positions) {
ib_alloc_t* heap_alloc;
/* Create a new fts_match_t instance. */
match = static_cast<fts_match_t*>(
ib_vector_push(query->matched, NULL));
match->start = 0;
match->doc_id = doc_id;
heap_alloc = ib_vector_allocator(query->matched);
/* Allocate from the same heap as the
parent container. */
match->positions = ib_vector_create(
heap_alloc, sizeof(ulint), 64);
query->total_size += sizeof(fts_match_t)
+ sizeof(ib_vector_t)
+ sizeof(ulint) * 64;
}
/* Unpack the positions within the document. */
while (*ptr) {
last_pos += fts_decode_vlc(&ptr);
/* Collect the matching word positions, for phrase
matching later. */
if (query->collect_positions) {
ib_vector_push(match->positions, &last_pos);
}
++freq;
}
/* End of list marker. */
last_pos = (ulint) -1;
if (query->collect_positions) {
ut_a(match != NULL);
ib_vector_push(match->positions, &last_pos);
}
/* Add the doc id to the doc freq rb tree, if the doc id
doesn't exist it will be created. */
doc_freq = fts_query_add_doc_freq(query, doc_freqs, doc_id);
/* Avoid duplicating frequency tally. */
if (doc_freq->freq == 0) {
doc_freq->freq = freq;
}
/* Skip the end of word position marker. */
++ptr;
/* Bytes decoded so far */
decoded = ptr - (byte*) data;
/* We simply collect the matching documents and the
positions here and match later. */
if (!query->collect_positions) {
/* We ignore error here and will check it later */
fts_query_process_doc_id(query, doc_id, 0);
/* Add the word to the document's matched RB tree. */
fts_query_add_word_to_document(query, doc_id, word);
}
}
/* Some sanity checks. */
ut_a(doc_id == node->last_doc_id);
if (query->total_size > fts_result_cache_limit) {
return(DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
} else {
return(DB_SUCCESS);
}
}
/*****************************************************************//**
Read the FTS INDEX row.
@return DB_SUCCESS if all go well. */
static
dberr_t
fts_query_read_node(
/*================*/
fts_query_t* query, /*!< in: query instance */
const fts_string_t* word, /*!< in: current word */
que_node_t* exp) /*!< in: query graph node */
{
int i;
int ret;
fts_node_t node;
ib_rbt_bound_t parent;
fts_word_freq_t* word_freq;
ibool skip = FALSE;
fts_string_t term;
byte buf[FTS_MAX_WORD_LEN + 1];
dberr_t error = DB_SUCCESS;
ut_a(query->cur_node->type == FTS_AST_TERM ||
query->cur_node->type == FTS_AST_TEXT);
memset(&node, 0, sizeof(node));
term.f_str = buf;
/* Need to consider the wildcard search case, the word frequency
is created on the search string not the actual word. So we need
to assign the frequency on search string behalf. */
if (query->cur_node->type == FTS_AST_TERM
&& query->cur_node->term.wildcard) {
term.f_len = query->cur_node->term.ptr->len;
ut_ad(FTS_MAX_WORD_LEN >= term.f_len);
memcpy(term.f_str, query->cur_node->term.ptr->str, term.f_len);
} else {
term.f_len = word->f_len;
ut_ad(FTS_MAX_WORD_LEN >= word->f_len);
memcpy(term.f_str, word->f_str, word->f_len);
}
/* Lookup the word in our rb tree, it must exist. */
ret = rbt_search(query->word_freqs, &parent, &term);
ut_a(ret == 0);
word_freq = rbt_value(fts_word_freq_t, parent.last);
/* Start from 1 since the first column has been read by the caller.
Also, we rely on the order of the columns projected, to filter
out ilists that are out of range and we always want to read
the doc_count irrespective of the suitablility of the row. */
for (i = 1; exp && !skip; exp = que_node_get_next(exp), ++i) {
dfield_t* dfield = que_node_get_val(exp);
byte* data = static_cast<byte*>(
dfield_get_data(dfield));
ulint len = dfield_get_len(dfield);
ut_a(len != UNIV_SQL_NULL);
/* Note: The column numbers below must match the SELECT. */
switch (i) {
case 1: /* DOC_COUNT */
word_freq->doc_count += mach_read_from_4(data);
break;
case 2: /* FIRST_DOC_ID */
node.first_doc_id = fts_read_doc_id(data);
/* Skip nodes whose doc ids are out range. */
if (query->oper == FTS_EXIST
&& query->upper_doc_id > 0
&& node.first_doc_id > query->upper_doc_id) {
skip = TRUE;
}
break;
case 3: /* LAST_DOC_ID */
node.last_doc_id = fts_read_doc_id(data);
/* Skip nodes whose doc ids are out range. */
if (query->oper == FTS_EXIST
&& query->lower_doc_id > 0
&& node.last_doc_id < query->lower_doc_id) {
skip = TRUE;
}
break;
case 4: /* ILIST */
error = fts_query_filter_doc_ids(
query, &word_freq->word, word_freq,
&node, data, len, FALSE);
break;
default:
ut_error;
}
}
if (!skip) {
/* Make sure all columns were read. */
ut_a(i == 5);
}
return error;
}
/*****************************************************************//**
Callback function to fetch the rows in an FTS INDEX record.
@return always returns TRUE */
static
ibool
fts_query_index_fetch_nodes(
/*========================*/
void* row, /*!< in: sel_node_t* */
void* user_arg) /*!< in: pointer to fts_fetch_t */
{
fts_string_t key;
sel_node_t* sel_node = static_cast<sel_node_t*>(row);
fts_fetch_t* fetch = static_cast<fts_fetch_t*>(user_arg);
fts_query_t* query = static_cast<fts_query_t*>(fetch->read_arg);
que_node_t* exp = sel_node->select_list;
dfield_t* dfield = que_node_get_val(exp);
void* data = dfield_get_data(dfield);
ulint dfield_len = dfield_get_len(dfield);
key.f_str = static_cast<byte*>(data);
key.f_len = dfield_len;
ut_a(dfield_len <= FTS_MAX_WORD_LEN);
/* Note: we pass error out by 'query->error' */
query->error = fts_query_read_node(query, &key, que_node_get_next(exp));
if (query->error != DB_SUCCESS) {
ut_ad(query->error == DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
return(FALSE);
} else {
return(TRUE);
}
}
/*****************************************************************//**
Calculate the inverse document frequency (IDF) for all the terms. */
static
void
fts_query_calculate_idf(
/*====================*/
fts_query_t* query) /*!< in: Query state */
{
const ib_rbt_node_t* node;
ib_uint64_t total_docs = query->total_docs;
/* We need to free any instances of fts_doc_freq_t that we
may have allocated. */
for (node = rbt_first(query->word_freqs);
node;
node = rbt_next(query->word_freqs, node)) {
fts_word_freq_t* word_freq;
word_freq = rbt_value(fts_word_freq_t, node);
if (word_freq->doc_count > 0) {
if (total_docs == word_freq->doc_count) {
/* QP assume ranking > 0 if we find
a match. Since Log10(1) = 0, we cannot
make IDF a zero value if do find a
word in all documents. So let's make
it an arbitrary very small number */
word_freq->idf = log10(1.0001);
} else {
word_freq->idf = log10(
total_docs
/ (double) word_freq->doc_count);
}
}
if (fts_enable_diag_print) {
fprintf(stderr,"'%s' -> " UINT64PF "/" UINT64PF
" %6.5lf\n",
word_freq->word.f_str,
query->total_docs, word_freq->doc_count,
word_freq->idf);
}
}
}
/*****************************************************************//**
Calculate the ranking of the document. */
static
void
fts_query_calculate_ranking(
/*========================*/
const fts_query_t* query, /*!< in: query state */
fts_ranking_t* ranking) /*!< in: Document to rank */
{
ulint pos = 0;
fts_string_t word;
/* At this stage, ranking->rank should not exceed the 1.0
bound */
ut_ad(ranking->rank <= 1.0 && ranking->rank >= -1.0);
ut_ad(rbt_size(query->word_map) == query->word_vector->size());
while (fts_ranking_words_get_next(query, ranking, &pos, &word)) {
int ret;
ib_rbt_bound_t parent;
double weight;
fts_doc_freq_t* doc_freq;
fts_word_freq_t* word_freq;
ret = rbt_search(query->word_freqs, &parent, &word);
/* It must exist. */
ut_a(ret == 0);
word_freq = rbt_value(fts_word_freq_t, parent.last);
ret = rbt_search(
word_freq->doc_freqs, &parent, &ranking->doc_id);
/* It must exist. */
ut_a(ret == 0);
doc_freq = rbt_value(fts_doc_freq_t, parent.last);
weight = (double) doc_freq->freq * word_freq->idf;
ranking->rank += (fts_rank_t) (weight * word_freq->idf);
}
}
/*****************************************************************//**
Add ranking to the result set. */
static
void
fts_query_add_ranking(
/*==================*/
fts_query_t* query, /*!< in: query state */
ib_rbt_t* ranking_tree, /*!< in: ranking tree */
const fts_ranking_t* new_ranking) /*!< in: ranking of a document */
{
ib_rbt_bound_t parent;
/* Lookup the ranking in our rb tree and add if it doesn't exist. */
if (rbt_search(ranking_tree, &parent, new_ranking) == 0) {
fts_ranking_t* ranking;
ranking = rbt_value(fts_ranking_t, parent.last);
ranking->rank += new_ranking->rank;
ut_a(ranking->words == NULL);
} else {
rbt_add_node(ranking_tree, &parent, new_ranking);
query->total_size += SIZEOF_RBT_NODE_ADD
+ sizeof(fts_ranking_t);
}
}
/*****************************************************************//**
Retrieve the FTS Relevance Ranking result for doc with doc_id
@return the relevance ranking value, 0 if no ranking value
present. */
float
fts_retrieve_ranking(
/*=================*/
fts_result_t* result, /*!< in: FTS result structure */
doc_id_t doc_id) /*!< in: doc_id of the item to retrieve */
{
ib_rbt_bound_t parent;
fts_ranking_t new_ranking;
DBUG_ENTER("fts_retrieve_ranking");
if (!result || !result->rankings_by_id) {
DBUG_RETURN(0);
}
new_ranking.doc_id = doc_id;
/* Lookup the ranking in our rb tree */
if (rbt_search(result->rankings_by_id, &parent, &new_ranking) == 0) {
fts_ranking_t* ranking;
ranking = rbt_value(fts_ranking_t, parent.last);
DBUG_RETURN(ranking->rank);
}
DBUG_RETURN(0);
}
/*****************************************************************//**
Create the result and copy the data to it. */
static
fts_result_t*
fts_query_prepare_result(
/*=====================*/
fts_query_t* query, /*!< in: Query state */
fts_result_t* result) /*!< in: result this can contain
data from a previous search on
another FTS index */
{
const ib_rbt_node_t* node;
bool result_is_null = false;
DBUG_ENTER("fts_query_prepare_result");
if (result == NULL) {
result = static_cast<fts_result_t*>(ut_malloc(sizeof(*result)));
memset(result, 0x0, sizeof(*result));
result->rankings_by_id = rbt_create(
sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
query->total_size += sizeof(fts_result_t) + SIZEOF_RBT_CREATE;
result_is_null = true;
}
if (query->flags == FTS_OPT_RANKING) {
fts_word_freq_t* word_freq;
ulint size = ib_vector_size(query->deleted->doc_ids);
fts_update_t* array =
(fts_update_t*) query->deleted->doc_ids->data;
node = rbt_first(query->word_freqs);
ut_ad(node);
word_freq = rbt_value(fts_word_freq_t, node);
for (node = rbt_first(word_freq->doc_freqs);
node;
node = rbt_next(word_freq->doc_freqs, node)) {
fts_doc_freq_t* doc_freq;
fts_ranking_t ranking;
doc_freq = rbt_value(fts_doc_freq_t, node);
/* Don't put deleted docs into result */
if (fts_bsearch(array, 0, static_cast<int>(size),
doc_freq->doc_id) >= 0) {
/* one less matching doc count */
--word_freq->doc_count;
continue;
}
ranking.doc_id = doc_freq->doc_id;
ranking.rank = static_cast<fts_rank_t>(doc_freq->freq);
ranking.words = NULL;
fts_query_add_ranking(query, result->rankings_by_id,
&ranking);
if (query->total_size > fts_result_cache_limit) {
query->error = DB_FTS_EXCEED_RESULT_CACHE_LIMIT;
fts_query_free_result(result);
DBUG_RETURN(NULL);
}
}
/* Calculate IDF only after we exclude the deleted items */
fts_query_calculate_idf(query);
node = rbt_first(query->word_freqs);
word_freq = rbt_value(fts_word_freq_t, node);
/* Calculate the ranking for each doc */
for (node = rbt_first(result->rankings_by_id);
node != NULL;
node = rbt_next(result->rankings_by_id, node)) {
fts_ranking_t* ranking;
ranking = rbt_value(fts_ranking_t, node);
ranking->rank = static_cast<fts_rank_t>(
ranking->rank * word_freq->idf * word_freq->idf);
}
DBUG_RETURN(result);
}
ut_a(rbt_size(query->doc_ids) > 0);
for (node = rbt_first(query->doc_ids);
node;
node = rbt_next(query->doc_ids, node)) {
fts_ranking_t* ranking;
ranking = rbt_value(fts_ranking_t, node);
fts_query_calculate_ranking(query, ranking);
// FIXME: I think we may requre this information to improve the
// ranking of doc ids which have more word matches from
// different FTS indexes.
/* We don't need these anymore free the resources. */
ranking->words = NULL;
if (!result_is_null) {
fts_query_add_ranking(query, result->rankings_by_id, ranking);
if (query->total_size > fts_result_cache_limit) {
query->error = DB_FTS_EXCEED_RESULT_CACHE_LIMIT;
fts_query_free_result(result);
DBUG_RETURN(NULL);
}
}
}
if (result_is_null) {
/* Use doc_ids directly */
rbt_free(result->rankings_by_id);
result->rankings_by_id = query->doc_ids;
query->doc_ids = NULL;
}
DBUG_RETURN(result);
}
/*****************************************************************//**
Get the result of the query. Calculate the similarity coefficient. */
static
fts_result_t*
fts_query_get_result(
/*=================*/
fts_query_t* query, /*!< in: query instance */
fts_result_t* result) /*!< in: result */
{
DBUG_ENTER("fts_query_get_result");
if (rbt_size(query->doc_ids) > 0 || query->flags == FTS_OPT_RANKING) {
/* Copy the doc ids to the result. */
result = fts_query_prepare_result(query, result);
} else {
/* Create an empty result instance. */
result = static_cast<fts_result_t*>(ut_malloc(sizeof(*result)));
memset(result, 0, sizeof(*result));
}
DBUG_RETURN(result);
}
/*****************************************************************//**
FTS Query free resources and reset. */
static
void
fts_query_free(
/*===========*/
fts_query_t* query) /*!< in: query instance to free*/
{
if (query->read_nodes_graph) {
fts_que_graph_free(query->read_nodes_graph);
}
if (query->root) {
fts_ast_free_node(query->root);
}
if (query->deleted) {
fts_doc_ids_free(query->deleted);
}
if (query->intersection) {
fts_query_free_doc_ids(query, query->intersection);
}
if (query->doc_ids) {
fts_query_free_doc_ids(query, query->doc_ids);
}
if (query->word_freqs) {
const ib_rbt_node_t* node;
/* We need to free any instances of fts_doc_freq_t that we
may have allocated. */
for (node = rbt_first(query->word_freqs);
node;
node = rbt_next(query->word_freqs, node)) {
fts_word_freq_t* word_freq;
word_freq = rbt_value(fts_word_freq_t, node);
/* We need to cast away the const. */
rbt_free(word_freq->doc_freqs);
}
rbt_free(query->word_freqs);
}
if (query->word_map) {
rbt_free(query->word_map);
}
if (query->word_vector) {
delete query->word_vector;
}
if (query->heap) {
mem_heap_free(query->heap);
}
memset(query, 0, sizeof(*query));
}
/*****************************************************************//**
Parse the query using flex/bison. */
static
fts_ast_node_t*
fts_query_parse(
/*============*/
fts_query_t* query, /*!< in: query instance */
byte* query_str, /*!< in: query string */
ulint query_len) /*!< in: query string length */
{
int error;
fts_ast_state_t state;
bool mode = query->boolean_mode;
DBUG_ENTER("fts_query_parse");
memset(&state, 0x0, sizeof(state));
/* Setup the scanner to use, this depends on the mode flag. */
state.lexer = fts_lexer_create(mode, query_str, query_len);
state.charset = query->fts_index_table.charset;
error = fts_parse(&state);
fts_lexer_free(state.lexer);
state.lexer = NULL;
/* Error during parsing ? */
if (error) {
/* Free the nodes that were allocated during parsing. */
fts_ast_state_free(&state);
} else {
query->root = state.root;
}
DBUG_RETURN(state.root);
}
/*******************************************************************//**
FTS Query optimization
Set FTS_OPT_RANKING if it is a simple term query */
static
void
fts_query_can_optimize(
/*===================*/
fts_query_t* query, /*!< in/out: query instance */
uint flags) /*!< In: FTS search mode */
{
fts_ast_node_t* node = query->root;
if (flags & FTS_EXPAND) {
return;
}
/* Check if it has only a term without oper */
ut_ad(node->type == FTS_AST_LIST);
node = node->list.head;
if (node != NULL && node->type == FTS_AST_TERM && node->next == NULL) {
query->flags = FTS_OPT_RANKING;
}
}
/*******************************************************************//**
Pre-process the query string
1) make it lower case
2) in boolean mode, if there is '-' or '+' that is immediately proceeded
and followed by valid word, make it a space
@return the processed string */
static
byte*
fts_query_str_preprocess(
/*=====================*/
const byte* query_str, /*!< in: FTS query */
ulint query_len, /*!< in: FTS query string len */
ulint *result_len, /*!< out: result string length */
CHARSET_INFO* charset, /*!< in: string charset */
bool boolean_mode) /*!< in: is boolean mode */
{
ulint cur_pos = 0;
ulint str_len;
byte* str_ptr;
bool in_phrase = false;
/* Convert the query string to lower case before parsing. We own
the ut_malloc'ed result and so remember to free it before return. */
str_len = query_len * charset->casedn_multiply + 1;
str_ptr = static_cast<byte*>(ut_malloc(str_len));
/* For binary collations, a case sensitive search is
performed. Hence don't convert to lower case. */
if (my_binary_compare(charset)) {
memcpy(str_ptr, query_str, query_len);
str_ptr[query_len]= 0;
*result_len= query_len;
} else {
*result_len = innobase_fts_casedn_str(
charset, const_cast<char*>
(reinterpret_cast<const char*>( query_str)),
query_len,
reinterpret_cast<char*>(str_ptr), str_len);
}
ut_ad(*result_len < str_len);
str_ptr[*result_len] = 0;
/* If it is boolean mode, no need to check for '-/+' */
if (!boolean_mode) {
return(str_ptr);
}
/* Otherwise, we travese the string to find any '-/+' that are
immediately proceeded and followed by valid search word.
NOTE: we should not do so for CJK languages, this should
be taken care of in our CJK implementation */
while (cur_pos < *result_len) {
fts_string_t str;
ulint offset;
ulint cur_len;
cur_len = innobase_mysql_fts_get_token(
charset, str_ptr + cur_pos, str_ptr + *result_len,
&str, &offset);
if (cur_len == 0 || str.f_str == NULL) {
/* No valid word found */
break;
}
/* Check if we are in a phrase, if so, no need to do
replacement of '-/+'. */
for (byte* ptr = str_ptr + cur_pos; ptr < str.f_str; ptr++) {
if ((char) (*ptr) == '"' ) {
in_phrase = !in_phrase;
}
}
/* Find those are not leading '-/+' and also not in a phrase */
if (cur_pos > 0 && str.f_str - str_ptr - cur_pos == 1
&& !in_phrase) {
char* last_op = reinterpret_cast<char*>(
str_ptr + cur_pos);
if (*last_op == '-' || *last_op == '+') {
*last_op = ' ';
}
}
cur_pos += cur_len;
}
return(str_ptr);
}
/*******************************************************************//**
FTS Query entry point.
@return DB_SUCCESS if successful otherwise error code */
UNIV_INTERN
dberr_t
fts_query(
/*======*/
trx_t* trx, /*!< in: transaction */
dict_index_t* index, /*!< in: The FTS index to search */
uint flags, /*!< in: FTS search mode */
const byte* query_str, /*!< in: FTS query */
ulint query_len, /*!< in: FTS query string len
in bytes */
fts_result_t** result) /*!< in/out: result doc ids */
{
fts_query_t query;
dberr_t error = DB_SUCCESS;
byte* lc_query_str;
ulint result_len;
bool boolean_mode;
trx_t* query_trx;
CHARSET_INFO* charset;
ulint start_time_ms;
bool will_be_ignored = false;
boolean_mode = flags & FTS_BOOL;
*result = NULL;
memset(&query, 0x0, sizeof(query));
query_trx = trx_allocate_for_background();
query_trx->op_info = "FTS query";
start_time_ms = ut_time_ms();
query.trx = query_trx;
query.index = index;
query.boolean_mode = boolean_mode;
query.deleted = fts_doc_ids_create();
query.cur_node = NULL;
query.fts_common_table.type = FTS_COMMON_TABLE;
query.fts_common_table.table_id = index->table->id;
query.fts_common_table.table = index->table;
charset = fts_index_get_charset(index);
query.fts_index_table.type = FTS_INDEX_TABLE;
query.fts_index_table.index_id = index->id;
query.fts_index_table.table_id = index->table->id;
query.fts_index_table.charset = charset;
query.fts_index_table.table = index->table;
query.word_map = rbt_create_arg_cmp(
sizeof(fts_string_t), innobase_fts_text_cmp,
(void *) charset);
query.word_vector = new word_vector_t;
query.error = DB_SUCCESS;
/* Setup the RB tree that will be used to collect per term
statistics. */
query.word_freqs = rbt_create_arg_cmp(
sizeof(fts_word_freq_t), innobase_fts_text_cmp,
(void*) charset);
query.total_size += SIZEOF_RBT_CREATE;
query.total_docs = dict_table_get_n_rows(index->table);
#ifdef FTS_DOC_STATS_DEBUG
if (ft_enable_diag_print) {
error = fts_get_total_word_count(
trx, query.index, &query.total_words);
if (error != DB_SUCCESS) {
goto func_exit;
}
fprintf(stderr, "Total docs: " UINT64PF " Total words: %lu\n",
query.total_docs, query.total_words);
}
#endif /* FTS_DOC_STATS_DEBUG */
query.fts_common_table.suffix = "DELETED";
/* Read the deleted doc_ids, we need these for filtering. */
error = fts_table_fetch_doc_ids(
NULL, &query.fts_common_table, query.deleted);
if (error != DB_SUCCESS) {
goto func_exit;
}
query.fts_common_table.suffix = "DELETED_CACHE";
error = fts_table_fetch_doc_ids(
NULL, &query.fts_common_table, query.deleted);
if (error != DB_SUCCESS) {
goto func_exit;
}
/* Get the deleted doc ids that are in the cache. */
fts_cache_append_deleted_doc_ids(
index->table->fts->cache, query.deleted->doc_ids);
DEBUG_SYNC_C("fts_deleted_doc_ids_append");
/* Sort the vector so that we can do a binary search over the ids. */
ib_vector_sort(query.deleted->doc_ids, fts_update_doc_id_cmp);
#if 0
/* Convert the query string to lower case before parsing. We own
the ut_malloc'ed result and so remember to free it before return. */
lc_query_str_len = query_len * charset->casedn_multiply + 1;
lc_query_str = static_cast<byte*>(ut_malloc(lc_query_str_len));
result_len = innobase_fts_casedn_str(
charset, (char*) query_str, query_len,
(char*) lc_query_str, lc_query_str_len);
ut_ad(result_len < lc_query_str_len);
lc_query_str[result_len] = 0;
#endif
lc_query_str = fts_query_str_preprocess(
query_str, query_len, &result_len, charset, boolean_mode);
query.heap = mem_heap_create(128);
/* Create the rb tree for the doc id (current) set. */
query.doc_ids = rbt_create(
sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
query.total_size += SIZEOF_RBT_CREATE;
/* Parse the input query string. */
if (fts_query_parse(&query, lc_query_str, result_len)) {
fts_ast_node_t* ast = query.root;
ast->trx = trx;
/* Optimize query to check if it's a single term */
fts_query_can_optimize(&query, flags);
DBUG_EXECUTE_IF("fts_instrument_result_cache_limit",
fts_result_cache_limit = 2048;
);
/* Traverse the Abstract Syntax Tree (AST) and execute
the query. */
query.error = fts_ast_visit(
FTS_NONE, ast, fts_query_visitor,
&query, &will_be_ignored);
if (query.error == DB_INTERRUPTED) {
error = DB_INTERRUPTED;
ut_free(lc_query_str);
goto func_exit;
}
/* If query expansion is requested, extend the search
with first search pass result */
if (query.error == DB_SUCCESS && (flags & FTS_EXPAND)) {
query.error = fts_expand_query(index, &query);
}
/* Calculate the inverse document frequency of the terms. */
if (query.error == DB_SUCCESS
&& query.flags != FTS_OPT_RANKING) {
fts_query_calculate_idf(&query);
}
/* Copy the result from the query state, so that we can
return it to the caller. */
if (query.error == DB_SUCCESS) {
*result = fts_query_get_result(&query, *result);
}
error = query.error;
} else {
/* still return an empty result set */
*result = static_cast<fts_result_t*>(
ut_malloc(sizeof(**result)));
memset(*result, 0, sizeof(**result));
}
if (trx_is_interrupted(trx)) {
error = DB_INTERRUPTED;
ut_free(lc_query_str);
if (*result) {
fts_query_free_result(*result);
}
goto func_exit;
}
ut_free(lc_query_str);
if (fts_enable_diag_print && (*result)) {
ulint diff_time = ut_time_ms() - start_time_ms;
fprintf(stderr, "FTS Search Processing time: %ld secs:"
" %ld millisec: row(s) %d \n",
diff_time / 1000, diff_time % 1000,
(*result)->rankings_by_id
? (int) rbt_size((*result)->rankings_by_id)
: -1);
/* Log memory consumption & result size */
ib_logf(IB_LOG_LEVEL_INFO,
"Full Search Memory: "
"%zu (bytes), Row: %lu .",
query.total_size,
(*result)->rankings_by_id
? rbt_size((*result)->rankings_by_id)
: 0);
}
func_exit:
fts_query_free(&query);
trx_free_for_background(query_trx);
return(error);
}
/*****************************************************************//**
FTS Query free result, returned by fts_query(). */
void
fts_query_free_result(
/*==================*/
fts_result_t* result) /*!< in: result instance to free.*/
{
if (result) {
if (result->rankings_by_id != NULL) {
rbt_free(result->rankings_by_id);
result->rankings_by_id = NULL;
}
if (result->rankings_by_rank != NULL) {
rbt_free(result->rankings_by_rank);
result->rankings_by_rank = NULL;
}
ut_free(result);
result = NULL;
}
}
/*****************************************************************//**
FTS Query sort result, returned by fts_query() on fts_ranking_t::rank. */
void
fts_query_sort_result_on_rank(
/*==========================*/
fts_result_t* result) /*!< out: result instance to sort.*/
{
const ib_rbt_node_t* node;
ib_rbt_t* ranked;
ut_a(result->rankings_by_id != NULL);
if (result->rankings_by_rank) {
rbt_free(result->rankings_by_rank);
}
ranked = rbt_create(sizeof(fts_ranking_t), fts_query_compare_rank);
/* We need to free any instances of fts_doc_freq_t that we
may have allocated. */
for (node = rbt_first(result->rankings_by_id);
node;
node = rbt_next(result->rankings_by_id, node)) {
fts_ranking_t* ranking;
ranking = rbt_value(fts_ranking_t, node);
ut_a(ranking->words == NULL);
rbt_insert(ranked, ranking, ranking);
}
/* Reset the current node too. */
result->current = NULL;
result->rankings_by_rank = ranked;
}
#ifdef UNIV_DEBUG
/*******************************************************************//**
A debug function to print result doc_id set. */
static
void
fts_print_doc_id(
/*=============*/
fts_query_t* query) /*!< in : tree that stores doc_ids.*/
{
const ib_rbt_node_t* node;
/* Iterate each member of the doc_id set */
for (node = rbt_first(query->doc_ids);
node;
node = rbt_next(query->doc_ids, node)) {
fts_ranking_t* ranking;
ranking = rbt_value(fts_ranking_t, node);
ib_logf(IB_LOG_LEVEL_INFO, "doc_ids info, doc_id: %ld \n",
(ulint) ranking->doc_id);
ulint pos = 0;
fts_string_t word;
while (fts_ranking_words_get_next(query, ranking, &pos, &word)) {
ib_logf(IB_LOG_LEVEL_INFO, "doc_ids info, value: %s \n", word.f_str);
}
}
}
#endif
/*************************************************************//**
This function implements a simple "blind" query expansion search:
words in documents found in the first search pass will be used as
search arguments to search the document again, thus "expand"
the search result set.
@return DB_SUCCESS if success, otherwise the error code */
static MY_ATTRIBUTE((nonnull, warn_unused_result))
dberr_t
fts_expand_query(
/*=============*/
dict_index_t* index, /*!< in: FTS index to search */
fts_query_t* query) /*!< in: FTS query instance */
{
const ib_rbt_node_t* node;
const ib_rbt_node_t* token_node;
fts_doc_t result_doc;
dberr_t error = DB_SUCCESS;
const fts_index_cache_t*index_cache;
/* If no doc is found in first search pass, return */
if (!rbt_size(query->doc_ids)) {
return(error);
}
/* Init "result_doc", to hold words from the first search pass */
fts_doc_init(&result_doc);
rw_lock_x_lock(&index->table->fts->cache->lock);
index_cache = fts_find_index_cache(index->table->fts->cache, index);
rw_lock_x_unlock(&index->table->fts->cache->lock);
ut_a(index_cache);
result_doc.tokens = rbt_create_arg_cmp(
sizeof(fts_token_t), innobase_fts_text_cmp,
(void*) index_cache->charset);
result_doc.charset = index_cache->charset;
query->total_size += SIZEOF_RBT_CREATE;
#ifdef UNIV_DEBUG
fts_print_doc_id(query);
#endif
for (node = rbt_first(query->doc_ids);
node;
node = rbt_next(query->doc_ids, node)) {
fts_ranking_t* ranking;
ulint pos;
fts_string_t word;
ulint prev_token_size;
ulint estimate_size;
prev_token_size = rbt_size(result_doc.tokens);
ranking = rbt_value(fts_ranking_t, node);
/* Fetch the documents with the doc_id from the
result of first seach pass. Since we do not
store document-to-word mapping, we need to
fetch the original document and parse them.
Future optimization could be done here if we
support some forms of document-to-word mapping */
fts_doc_fetch_by_doc_id(NULL, ranking->doc_id, index,
FTS_FETCH_DOC_BY_ID_EQUAL,
fts_query_expansion_fetch_doc,
&result_doc);
/* Remove words that have already been searched in the
first pass */
pos = 0;
while (fts_ranking_words_get_next(query, ranking, &pos,
&word)) {
ibool ret;
ret = rbt_delete(result_doc.tokens, &word);
/* The word must exist in the doc we found */
if (!ret) {
ib_logf(IB_LOG_LEVEL_ERROR, "Did not "
"find word %s in doc %ld for query "
"expansion search.\n", word.f_str,
(ulint) ranking->doc_id);
}
}
/* Estimate memory used, see fts_process_token and fts_token_t.
We ignore token size here. */
estimate_size = (rbt_size(result_doc.tokens) - prev_token_size)
* (SIZEOF_RBT_NODE_ADD + sizeof(fts_token_t)
+ sizeof(ib_vector_t) + sizeof(ulint) * 32);
query->total_size += estimate_size;
if (query->total_size > fts_result_cache_limit) {
error = DB_FTS_EXCEED_RESULT_CACHE_LIMIT;
goto func_exit;
}
}
/* Search the table the second time with expanded search list */
for (token_node = rbt_first(result_doc.tokens);
token_node;
token_node = rbt_next(result_doc.tokens, token_node)) {
fts_token_t* mytoken;
mytoken = rbt_value(fts_token_t, token_node);
ut_ad(mytoken->text.f_str[mytoken->text.f_len] == 0);
fts_query_add_word_freq(query, &mytoken->text);
error = fts_query_union(query, &mytoken->text);
if (error != DB_SUCCESS) {
break;
}
}
func_exit:
fts_doc_free(&result_doc);
return(error);
}
/*************************************************************//**
This function finds documents that contain all words in a
phrase or proximity search. And if proximity search, verify
the words are close enough to each other, as in specified distance.
This function is called for phrase and proximity search.
@return TRUE if documents are found, FALSE if otherwise */
static
ibool
fts_phrase_or_proximity_search(
/*===========================*/
fts_query_t* query, /*!< in/out: query instance.
query->doc_ids might be instantiated
with qualified doc IDs */
ib_vector_t* tokens) /*!< in: Tokens contain words */
{
ulint n_matched;
ulint i;
ibool matched = FALSE;
ulint num_token = ib_vector_size(tokens);
fts_match_t* match[MAX_PROXIMITY_ITEM];
ibool end_list = FALSE;
/* Number of matched documents for the first token */
n_matched = ib_vector_size(query->match_array[0]);
/* We have a set of match list for each word, we shall
walk through the list and find common documents that
contain all the matching words. */
for (i = 0; i < n_matched; i++) {
ulint j;
ulint k = 0;
fts_proximity_t qualified_pos;
match[0] = static_cast<fts_match_t*>(
ib_vector_get(query->match_array[0], i));
/* For remaining match list for the token(word), we
try to see if there is a document with the same
doc id */
for (j = 1; j < num_token; j++) {
match[j] = static_cast<fts_match_t*>(
ib_vector_get(query->match_array[j], k));
while (match[j]->doc_id < match[0]->doc_id
&& k < ib_vector_size(query->match_array[j])) {
match[j] = static_cast<fts_match_t*>(
ib_vector_get(
query->match_array[j], k));
k++;
}
if (match[j]->doc_id > match[0]->doc_id) {
/* no match */
if (query->flags & FTS_PHRASE) {
match[0]->doc_id = 0;
}
break;
}
if (k == ib_vector_size(query->match_array[j])) {
end_list = TRUE;
if (match[j]->doc_id != match[0]->doc_id) {
/* no match */
if (query->flags & FTS_PHRASE) {
ulint s;
match[0]->doc_id = 0;
for (s = i + 1; s < n_matched;
s++) {
match[0] = static_cast<
fts_match_t*>(
ib_vector_get(
query->match_array[0],
s));
match[0]->doc_id = 0;
}
}
goto func_exit;
}
}
/* FIXME: A better solution will be a counter array
remember each run's last position. So we don't
reset it here very time */
k = 0;
}
if (j != num_token) {
continue;
}
/* For this matching doc, we need to further
verify whether the words in the doc are close
to each other, and within the distance specified
in the proximity search */
if (query->flags & FTS_PHRASE) {
matched = TRUE;
} else if (fts_proximity_get_positions(
match, num_token, ULINT_MAX, &qualified_pos)) {
/* Fetch the original documents and count the
words in between matching words to see that is in
specified distance */
if (fts_query_is_in_proximity_range(
query, match, &qualified_pos)) {
/* If so, mark we find a matching doc */
query->error = fts_query_process_doc_id(
query, match[0]->doc_id, 0);
if (query->error != DB_SUCCESS) {
matched = FALSE;
goto func_exit;
}
matched = TRUE;
for (ulint z = 0; z < num_token; z++) {
fts_string_t* token;
token = static_cast<fts_string_t*>(
ib_vector_get(tokens, z));
fts_query_add_word_to_document(
query, match[0]->doc_id, token);
}
}
}
if (end_list) {
break;
}
}
func_exit:
return(matched);
}
/*************************************************************//**
This function checks whether words in result documents are close to
each other (within proximity range as specified by "distance").
If "distance" is MAX_ULINT, then it will find all combinations of
positions of matching words and store min and max positions
in the "qualified_pos" for later verification.
@return true if words are close to each other, false if otherwise */
static
bool
fts_proximity_get_positions(
/*========================*/
fts_match_t** match, /*!< in: query instance */
ulint num_match, /*!< in: number of matching
items */
ulint distance, /*!< in: distance value
for proximity search */
fts_proximity_t* qualified_pos) /*!< out: the position info
records ranges containing
all matching words. */
{
ulint i;
ulint idx[MAX_PROXIMITY_ITEM];
ulint num_pos[MAX_PROXIMITY_ITEM];
ulint min_idx;
qualified_pos->n_pos = 0;
ut_a(num_match <= MAX_PROXIMITY_ITEM);
/* Each word could appear multiple times in a doc. So
we need to walk through each word's position list, and find
closest distance between different words to see if
they are in the proximity distance. */
/* Assume each word's position list is sorted, we
will just do a walk through to all words' lists
similar to a the merge phase of a merge sort */
for (i = 0; i < num_match; i++) {
/* idx is the current position we are checking
for a particular word */
idx[i] = 0;
/* Number of positions for this word */
num_pos[i] = ib_vector_size(match[i]->positions);
}
/* Start with the first word */
min_idx = 0;
while (idx[min_idx] < num_pos[min_idx]) {
ulint position[MAX_PROXIMITY_ITEM];
ulint min_pos = ULINT_MAX;
ulint max_pos = 0;
/* Check positions in each word position list, and
record the max/min position */
for (i = 0; i < num_match; i++) {
position[i] = *(ulint*) ib_vector_get_const(
match[i]->positions, idx[i]);
if (position[i] == ULINT_UNDEFINED) {
break;
}
if (position[i] < min_pos) {
min_pos = position[i];
min_idx = i;
}
if (position[i] > max_pos) {
max_pos = position[i];
}
}
/* If max and min position are within range, we
find a good match */
if (max_pos - min_pos <= distance
&& (i >= num_match || position[i] != ULINT_UNDEFINED)) {
/* The charset has variable character
length encoding, record the min_pos and
max_pos, we will need to verify the actual
number of characters */
qualified_pos->min_pos.push_back(min_pos);
qualified_pos->max_pos.push_back(max_pos);
qualified_pos->n_pos++;
}
/* Otherwise, move to the next position is the
list for the word with the smallest position */
idx[min_idx]++;
}
return(qualified_pos->n_pos != 0);
}
|