-
-
Notifications
You must be signed in to change notification settings - Fork 625
Expand file tree
/
Copy pathsphinx.cpp
More file actions
13825 lines (11118 loc) · 424 KB
/
sphinx.cpp
File metadata and controls
13825 lines (11118 loc) · 424 KB
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
//
// Copyright (c) 2017-2026, Manticore Software LTD (https://manticoresearch.com)
// Copyright (c) 2001-2016, Andrew Aksyonoff
// Copyright (c) 2008-2016, Sphinx Technologies Inc
// All rights reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License. You should have
// received a copy of the GPL license along with this program; if you
// did not, you can find it at http://www.gnu.org/
//
#include "sphinx.h"
#include "dict/stem/sphinxstem.h"
#include "sphinxquery/sphinxquery.h"
#include "sphinxquery/xqparser.h"
#include "sphinxutils.h"
#include "sphinxsort.h"
#include "fileutils.h"
#include "sphinxexpr.h"
#include "sphinxfilter.h"
#include "sphinxint.h"
#include "sphinxsearch.h"
#include "searchnode.h"
#include "sphinxjson.h"
#include "sphinxqcache.h"
#include "icu.h"
#include "jieba.h"
#include "attribute.h"
#include "secondaryindex.h"
#include "docidlookup.h"
#include "histogram.h"
#include "killlist.h"
#include "docstore.h"
#include "global_idf.h"
#include "indexformat.h"
#include "indexcheck.h"
#include "coroutine.h"
#include "columnarlib.h"
#include "columnarmisc.h"
#include "columnarfilter.h"
#include "mini_timer.h"
#include "sphinx_alter.h"
#include "conversion.h"
#include "binlog.h"
#include "embeddingutils.h"
#include "task_info.h"
#include "client_task_info.h"
#include "chunksearchctx.h"
#include "std/lrucache.h"
#include "std/sys.h"
#include "indexfiles.h"
#include "task_dispatcher.h"
#include "secondarylib.h"
#include "knnlib.h"
#include "attrindex_merge.h"
#include "knnmisc.h"
#include "querycontext.h"
#include "dict/infix/infix_builder.h"
#include "skip_cache.h"
#include "jsonsi.h"
#include "tracer.h"
#include <errno.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <math.h>
#include <algorithm>
#if WITH_RE2
#include <string>
#include <re2/re2.h>
#endif
#if !_WIN32
#include <unistd.h>
#include <sys/time.h>
#endif
/////////////////////////////////////////////////////////////////////////////
// logf() is not there sometimes (eg. Solaris 9)
#if !_WIN32 && !HAVE_LOGF
static inline float logf ( float v )
{
return (float) log ( v );
}
#endif
#if _WIN32
void localtime_r ( const time_t * clock, struct tm * res )
{
tm * pRes = localtime ( clock );
if ( pRes )
*res = *pRes;
}
void gmtime_r ( const time_t * clock, struct tm * res )
{
tm * pRes = gmtime ( clock );
if ( pRes )
*res = *pRes;
}
#endif
#include <boost/preprocessor/repetition/repeat.hpp>
#include "attrindex_builder.h"
#include "queryfilter.h"
#include "indexing_sources/source_document.h"
#include "indexing_sources/source_stats.h"
#include "dict/dict_base.h"
#include "dict/bin.h"
/////////////////////////////////////////////////////////////////////////////
// GLOBALS
/////////////////////////////////////////////////////////////////////////////
const char * MAGIC_WORD_SENTENCE = "\3sentence"; // emitted from source on sentence boundary, stored in dictionary
const char * MAGIC_WORD_PARAGRAPH = "\3paragraph"; // emitted from source on paragraph boundary, stored in dictionary
bool g_bJsonStrict = false;
bool g_bJsonAutoconvNumbers = false;
bool g_bJsonKeynamesToLowercase = false;
static const int MIN_READ_BUFFER = 8192;
static const int MIN_READ_UNHINTED = 1024;
static int g_iReadUnhinted = DEFAULT_READ_UNHINTED;
static bool g_bPseudoSharding = true;
static int g_iPseudoShardingThresh = 8192;
static BuildBufferSettings_t g_tMergeSettings;
static int g_iLowPriorityDivisor = 10; // how smaller quantum low-priority tasks take comparing to normal in case of load
static bool LOG_LEVEL_SPLIT_QUERY = val_from_env ( "MANTICORE_LOG_SPLIT_QUERY", false ); // verbose logging split query events, ruled by this env variable
#define LOG_COMPONENT_QUERYINFO __LINE__ << " "
#define QUERYINFO LOGINFO ( SPLIT_QUERY, QUERYINFO )
// quick hack for indexer crash reporting
// one day, these might turn into a callback or something
int64_t g_iIndexerCurrentDocID = 0;
int64_t g_iIndexerCurrentHits = 0;
int64_t g_iIndexerCurrentRangeMin = 0;
int64_t g_iIndexerCurrentRangeMax = 0;
int64_t g_iIndexerPoolStartDocID = 0;
int64_t g_iIndexerPoolStartHit = 0;
static bool IndexBuildDone ( const BuildHeader_t & tBuildHeader, const WriteHeader_t & tWriteHeader, const CSphString & sFileName, CSphString & sError );
/////////////////////////////////////////////////////////////////////////////
// COMPILE-TIME CHECKS
/////////////////////////////////////////////////////////////////////////////
STATIC_SIZE_ASSERT ( SphOffset_t, 8 );
/////////////////////////////////////////////////////////////////////////////
// INTERNAL SPHINX CLASSES DECLARATIONS
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static const char * g_dRankerNames[] =
{
"proximity_bm25",
"bm25",
"none",
"wordcount",
"proximity",
"matchany",
"fieldmask",
"sph04",
"expr",
"export",
NULL
};
const char * sphGetRankerName ( ESphRankMode eRanker )
{
if ( eRanker<SPH_RANK_PROXIMITY_BM25 || eRanker>=SPH_RANK_TOTAL )
return NULL;
return g_dRankerNames[eRanker];
}
/////////////////////////////////////////////////////////////////////
/// everything required to setup search term
class DiskIndexQwordSetup_c final : public ISphQwordSetup
{
public:
DiskIndexQwordSetup_c ( DataReaderFactoryPtr_c pDoclist, DataReaderFactoryPtr_c pHitlist, const BYTE * pSkips, int iSkiplistBlockSize, bool bSetupReaders, RowID_t iRowsCount )
: m_pDoclist ( std::move ( pDoclist ) )
, m_pHitlist ( std::move ( pHitlist ) )
, m_pSkips ( pSkips )
, m_iSkiplistBlockSize ( iSkiplistBlockSize )
, m_bSetupReaders ( bSetupReaders )
, m_iRowsCount ( iRowsCount )
{}
ISphQword * QwordSpawn ( const XQKeyword_t & tWord ) const final;
bool QwordSetup ( ISphQword * ) const final;
bool Setup ( ISphQword * ) const;
ISphQword * ScanSpawn ( int iAtomPos ) const final;
private:
DataReaderFactoryPtr_c m_pDoclist;
DataReaderFactoryPtr_c m_pHitlist;
const BYTE * m_pSkips;
int m_iSkiplistBlockSize = 0;
bool m_bSetupReaders = false;
RowID_t m_iRowsCount = INVALID_ROWID;
private:
bool SetupWithWrd ( const DiskIndexQwordTraits_c& tWord, DictEntry_t& tRes ) const;
bool SetupWithCrc ( const DiskIndexQwordTraits_c& tWord, DictEntry_t& tRes ) const;
};
/// query word from the searcher's point of view
template < bool INLINE_HITS, bool DISABLE_HITLIST_SEEK >
class DiskIndexQword_c : public DiskIndexQwordTraits_c
{
public:
DiskIndexQword_c ( bool bUseMinibuffer, bool bExcluded, int64_t iIndexId )
: DiskIndexQwordTraits_c ( bUseMinibuffer, bExcluded )
, m_iIndexId ( iIndexId )
{}
~DiskIndexQword_c()
{
if ( m_bSkipFromCache )
{
SkipCache::Release ( { m_iIndexId, m_uWordID } );
m_pSkipData = nullptr;
m_bSkipFromCache = false;
}
}
void Reset () final
{
if ( m_rdDoclist )
m_rdDoclist->Reset ();
if ( m_rdHitlist )
m_rdHitlist->Reset ();
ResetDecoderState();
}
void GetHitlistEntry ()
{
assert ( !m_bHitlistOver );
DWORD iDelta = m_rdHitlist->UnzipInt ();
if ( iDelta )
{
m_iHitPos += iDelta;
} else
{
m_iHitPos = EMPTY_HIT;
#ifndef NDEBUG
m_bHitlistOver = true;
#endif
}
}
RowID_t AdvanceTo ( RowID_t tRowID ) final
{
if ( m_tDoc.m_tRowID!=INVALID_ROWID && tRowID<=m_tDoc.m_tRowID )
return m_tDoc.m_tRowID;
bool bRewound = HintRowID (tRowID);
if ( bRewound || m_tDoc.m_tRowID==INVALID_ROWID )
ReadNext();
while ( m_tDoc.m_tRowID < tRowID )
ReadNext();
return m_tDoc.m_tRowID;
}
bool HintRowID ( RowID_t tRowID ) final
{
// tricky bit
// FindSpan() will match a block where tBaseRowIDPlus1[i] <= tRowID < tBaseRowIDPlus1[i+1]
// meaning that the subsequent ids decoded will be strictly > RefValue
// meaning that if previous (!) block ends with tRowID exactly,
// and we use tRowID itself as RefValue, that document gets lost!
// first check if we're still inside the last block
if ( m_iSkipListBlock==-1 )
{
if ( !m_pSkipData )
return true;
m_iSkipListBlock = FindSpan ( m_pSkipData->m_dSkiplist, tRowID );
if ( m_iSkipListBlock<0 )
return false;
}
else
{
assert(m_pSkipData);
const auto & dSkiplist = m_pSkipData->m_dSkiplist;
if ( m_iSkipListBlock < dSkiplist.GetLength()-1 )
{
int iNextBlock = m_iSkipListBlock+1;
RowID_t tNextBlockRowID = dSkiplist[iNextBlock].m_tBaseRowIDPlus1;
if ( tRowID>=tNextBlockRowID )
{
auto dSkips = VecTraits_T<SkiplistEntry_t> ( &dSkiplist[iNextBlock], dSkiplist.GetLength()-iNextBlock );
m_iSkipListBlock = FindSpan ( dSkips, tRowID );
if ( m_iSkipListBlock<0 )
return false;
m_iSkipListBlock += iNextBlock;
}
}
else // we're already at our last block, no need to search
return false;
}
assert(m_pSkipData);
const SkiplistEntry_t & t = m_pSkipData->m_dSkiplist[m_iSkipListBlock];
if ( t.m_iOffset<=m_rdDoclist->GetPos() )
return false;
m_rdDoclist->SeekTo ( t.m_iOffset, -1 );
m_tDoc.m_tRowID = t.m_tBaseRowIDPlus1-1;
m_uHitPosition = m_iHitlistPos = t.m_iBaseHitlistPos;
return true;
}
const CSphMatch & GetNextDoc() override
{
ReadNext();
return m_tDoc;
}
void SeekHitlist ( SphOffset_t uOff ) final
{
if ( uOff >> 63 )
{
m_uHitState = 1;
m_uInlinedHit = (DWORD)uOff; // truncate high dword
} else
{
m_uHitState = 0;
m_iHitPos = EMPTY_HIT;
if constexpr ( DISABLE_HITLIST_SEEK )
assert ( m_rdHitlist->GetPos()==uOff ); // make sure we're where caller thinks we are.
else
m_rdHitlist->SeekTo ( uOff, READ_NO_SIZE_HINT );
}
#ifndef NDEBUG
m_bHitlistOver = false;
#endif
}
Hitpos_t GetNextHit () final
{
assert ( m_bHasHitlist );
switch ( m_uHitState )
{
case 0: // read hit from hitlist
GetHitlistEntry ();
return m_iHitPos;
case 1: // return inlined hit
m_uHitState = 2;
return m_uInlinedHit;
case 2: // return end-of-hitlist marker after inlined hit
#ifndef NDEBUG
m_bHitlistOver = true;
#endif
m_uHitState = 0;
return EMPTY_HIT;
}
sphDie ( "INTERNAL ERROR: impossible hit emitter state" );
return EMPTY_HIT;
}
bool Setup ( const DiskIndexQwordSetup_c * pSetup ) override
{
return pSetup->Setup ( this );
}
using is_worddict = std::integral_constant<bool, !DISABLE_HITLIST_SEEK>;
private:
int m_iSkipListBlock = -1;
inline void ReadNext()
{
RowID_t uDelta = m_rdDoclist->UnzipRowid();
if ( uDelta )
{
m_bAllFieldsKnown = false;
m_tDoc.m_tRowID += uDelta;
if_const ( INLINE_HITS )
{
m_uMatchHits = m_rdDoclist->UnzipInt();
const DWORD uFirst = m_rdDoclist->UnzipInt();
if ( m_uMatchHits==1 && m_bHasHitlist )
{
DWORD uField = m_rdDoclist->UnzipInt(); // field and end marker
m_iHitlistPos = uFirst | ( uField << 23 ) | ( U64C(1)<<63 );
m_dQwordFields.UnsetAll();
// want to make sure bad field data not cause crash
m_dQwordFields.Set ( ( uField >> 1 ) & ( (DWORD)SPH_MAX_FIELDS-1 ) );
m_bAllFieldsKnown = true;
} else
{
m_dQwordFields.Assign32 ( uFirst );
m_uHitPosition += m_rdDoclist->UnzipOffset();
m_iHitlistPos = m_uHitPosition;
}
} else
{
SphOffset_t iDeltaPos = m_rdDoclist->UnzipOffset();
assert ( iDeltaPos>=0 );
m_iHitlistPos += iDeltaPos;
m_dQwordFields.Assign32 ( m_rdDoclist->UnzipInt() );
m_uMatchHits = m_rdDoclist->UnzipInt();
}
} else
m_tDoc.m_tRowID = INVALID_ROWID;
}
private:
int64_t m_iIndexId = 0;
};
DiskIndexQwordTraits_c * sphCreateDiskIndexQword ( bool bInlineHits )
{
if ( bInlineHits )
return new DiskIndexQword_c<true,false> ( false, false, 0 );
return new DiskIndexQword_c<false,false> ( false, false, 0 );
}
/////////////////////////////////////////////////////////////////////////////
#define WITH_QWORD(INDEX, NO_SEEK, NAME, ACTION) \
do if ( (( const CSphIndex_VLN *)INDEX)->m_tSettings.m_eHitFormat==SPH_HIT_FORMAT_INLINE ) \
{ using NAME = DiskIndexQword_c < true, NO_SEEK >; ACTION; } \
else \
{ using NAME = DiskIndexQword_c < false, NO_SEEK >; ACTION; } \
while(0)
/////////////////////////////////////////////////////////////////////////////
// duplicated in sphinxformat.cpp
struct Slice64_t
{
uint64_t m_uOff;
int m_iLen;
};
// duplicated in sphinxformat.cpp
struct DiskSubstringPayload_t : public ISphSubstringPayload
{
explicit DiskSubstringPayload_t ( int iDoclists )
: m_dDoclist ( iDoclists )
{}
CSphFixedVector<Slice64_t> m_dDoclist;
};
template < bool INLINE_HITS >
class DiskPayloadQword_c : public DiskIndexQword_c<INLINE_HITS, false>
{
typedef DiskIndexQword_c<INLINE_HITS, false> BASE;
public:
DiskPayloadQword_c ( const DiskSubstringPayload_t * pPayload, bool bExcluded, DataReaderFactory_c * pDoclist, DataReaderFactory_c * pHitlist, int64_t iIndexId )
: BASE ( true, bExcluded, iIndexId )
{
m_pPayload = pPayload;
this->m_iDocs = m_pPayload->m_iTotalDocs;
this->m_iHits = m_pPayload->m_iTotalHits;
m_iDoclist = 0;
this->SetDocReader ( pDoclist );
this->SetHitReader ( pHitlist );
}
const CSphMatch & GetNextDoc() final
{
const CSphMatch & tMatch = BASE::GetNextDoc();
assert ( &tMatch==&this->m_tDoc );
if ( tMatch.m_tRowID==INVALID_ROWID && m_iDoclist<m_pPayload->m_dDoclist.GetLength() )
{
BASE::ResetDecoderState();
SetupReader();
BASE::GetNextDoc();
assert ( this->m_tDoc.m_tRowID!=INVALID_ROWID );
}
return this->m_tDoc;
}
bool Setup ( const DiskIndexQwordSetup_c * ) final
{
if ( m_iDoclist>=m_pPayload->m_dDoclist.GetLength() )
return false;
SetupReader();
return true;
}
private:
void SetupReader ()
{
uint64_t uDocOff = m_pPayload->m_dDoclist[m_iDoclist].m_uOff;
int iHint = m_pPayload->m_dDoclist[m_iDoclist].m_iLen;
m_iDoclist++;
this->m_rdDoclist->SeekTo ( uDocOff, iHint );
}
const DiskSubstringPayload_t * m_pPayload;
int m_iDoclist;
};
//////////////////////////////////////////////////////////////////////////
const char* CheckFmtMagic ( DWORD uHeader )
{
if ( uHeader!=INDEX_MAGIC_HEADER )
{
FlipEndianness ( &uHeader );
if ( uHeader==INDEX_MAGIC_HEADER )
#if USE_LITTLE_ENDIAN
return "This instance is working on little-endian platform, but %s seems built on big-endian host.";
#else
return "This instance is working on big-endian platform, but %s seems built on little-endian host.";
#endif
else
return "%s is invalid header file (too old table version?)";
}
return nullptr;
}
/// this pseudo-index used to store and manage the tokenizer
/// without any footprint in real files
//////////////////////////////////////////////////////////////////////////
class CSphTokenizerIndex : public CSphIndexStub
{
public:
CSphTokenizerIndex ( CSphString sIndexName ) : CSphIndexStub ( std::move ( sIndexName ), "" ) {}
bool GetKeywords ( CSphVector <CSphKeywordInfo> & , const char * , const GetKeywordsSettings_t & tSettings, CSphString * ) const final ;
Bson_t ExplainQuery ( const CSphString & sQuery ) const final;
};
bool CSphTokenizerIndex::GetKeywords ( CSphVector <CSphKeywordInfo> & dKeywords, const char * szQuery, const GetKeywordsSettings_t & tSettings, CSphString * ) const
{
// short-cut if no query or keywords to fill
if ( !szQuery || !szQuery[0] )
return true;
TokenizerRefPtr_c pTokenizer = m_pTokenizer->Clone ( SPH_CLONE_INDEX );
pTokenizer->EnableTokenizedMultiformTracking ();
// need to support '*' and '=' but not the other specials
// so m_pQueryTokenizer does not work for us, gotta clone and setup one manually
DictRefPtr_c pDict = GetStatelessDict ( m_pDict );
if ( IsStarDict ( pDict->GetSettings().m_bWordDict ) )
{
pTokenizer->AddPlainChars ( "*" );
SetupStarDict ( pDict, false );
}
if ( m_tSettings.m_bIndexExactWords )
{
pTokenizer->AddSpecials ( "=" );
SetupExactDict ( pDict );
}
dKeywords.Resize ( 0 );
CSphVector<BYTE> dFiltered;
const BYTE * sModifiedQuery = (const BYTE *)szQuery;
FieldFilterOptions_t tFFOptions { tSettings.m_eJiebaMode };
if ( m_pFieldFilter && szQuery && m_pFieldFilter->Clone ( &tFFOptions )->Apply ( sModifiedQuery, dFiltered, true ) )
sModifiedQuery = dFiltered.Begin();
pTokenizer->SetBuffer ( sModifiedQuery, (int) strlen ( (const char*)sModifiedQuery) );
CSphTemplateQueryFilter tAotFilter;
tAotFilter.m_pTokenizer = std::move ( pTokenizer );
tAotFilter.m_pDict = std::move ( pDict );
tAotFilter.m_pSettings = &m_tSettings;
tAotFilter.m_tFoldSettings = tSettings;
tAotFilter.m_tFoldSettings.m_bStats = false;
tAotFilter.m_tFoldSettings.m_bFoldWildcards = true;
ExpansionContext_t tExpCtx;
tAotFilter.GetKeywords ( dKeywords, tExpCtx );
return true;
}
std::unique_ptr<CSphIndex> sphCreateIndexTemplate ( CSphString sIndexName )
{
return std::make_unique<CSphTokenizerIndex> ( std::move ( sIndexName ) );
}
Bson_t CSphTokenizerIndex::ExplainQuery ( const CSphString & sQuery ) const
{
bool bWordDict = m_pDict->GetSettings().m_bWordDict;
WordlistStub_c tWordlist;
ExplainQueryArgs_t tArgs;
tArgs.m_szQuery = sQuery.cstr();
tArgs.m_pDict = GetStatelessDict ( m_pDict );
if ( IsStarDict ( bWordDict ) )
SetupStarDict ( tArgs.m_pDict, m_tSettings.m_iMinInfixLen>0 );
if ( m_tSettings.m_bIndexExactWords )
SetupExactDict ( tArgs.m_pDict );
if ( m_pFieldFilter )
tArgs.m_pFieldFilter = m_pFieldFilter->Clone();
tArgs.m_pSettings = &m_tSettings;
tArgs.m_pWordlist = &tWordlist;
tArgs.m_pQueryTokenizer = m_pQueryTokenizer;
tArgs.m_iExpandKeywords = m_tMutableSettings.m_iExpandKeywords;
tArgs.m_iExpansionLimit = m_iExpansionLimit;
tArgs.m_bExpandPrefix = ( bWordDict && IsStarDict ( bWordDict ) );
return Explain ( tArgs );
}
//////////////////////////////////////////////////////////////////////////
UpdateContext_t::UpdateContext_t ( AttrUpdateInc_t & tUpd, const ISphSchema & tSchema )
: m_tUpd ( tUpd )
, m_tSchema ( tSchema )
, m_iStride ( tSchema.GetRowSize() )
, m_dUpdatedAttrs ( tUpd.m_pUpdate->m_dAttributes.GetLength() )
, m_dSchemaUpdateMask ( tSchema.GetAttrsCount() )
{}
//////////////////////////////////////////////////////////////////////////
bool Update_CheckAttributes ( const CSphAttrUpdate & tUpd, const ISphSchema & tSchema, CSphString & sError, CSphString & sWarning )
{
for ( const auto & tUpdAttr : tUpd.m_dAttributes )
{
const CSphString & sUpdAttrName = tUpdAttr.m_sName;
int iUpdAttrId = tSchema.GetAttrIndex ( sUpdAttrName.cstr() );
// try to find JSON attribute with a field
if ( iUpdAttrId<0 )
{
CSphString sJsonCol;
if ( sphJsonNameSplit ( sUpdAttrName.cstr(), nullptr, &sJsonCol ) )
iUpdAttrId = tSchema.GetAttrIndex ( sJsonCol.cstr() );
}
if ( iUpdAttrId<0 )
{
if ( tUpd.m_bIgnoreNonexistent )
continue;
// if it's a field but not an attribute, reject
bool bIsField = ( tSchema.GetField ( sUpdAttrName.cstr() ) != nullptr );
if ( bIsField )
{
sError.SetSprintf ( "attribute '%s' can not be updated (full-text field)", sUpdAttrName.cstr() );
return false;
}
sError.SetSprintf ( "attribute '%s' not found", sUpdAttrName.cstr() );
return false;
}
// forbid updates on non-int columns
const CSphColumnInfo & tCol = tSchema.GetAttr ( iUpdAttrId );
switch ( tCol.m_eAttrType )
{
case SPH_ATTR_BOOL:
case SPH_ATTR_INTEGER:
case SPH_ATTR_TIMESTAMP:
case SPH_ATTR_UINT32SET:
case SPH_ATTR_INT64SET:
case SPH_ATTR_FLOAT_VECTOR:
case SPH_ATTR_BIGINT:
case SPH_ATTR_FLOAT:
case SPH_ATTR_JSON:
break;
// if string attribute is also a full-text field, allow update but warn
case SPH_ATTR_STRING:
if ( tSchema.GetField ( sUpdAttrName.cstr() )!=nullptr )
{
if ( sWarning.IsEmpty() )
sWarning.SetSprintf ( "attribute '%s' is updated, but full-text field is not (recommended to use REPLACE instead)", sUpdAttrName.cstr() );
else
sWarning.SetSprintf ( "%s; attribute '%s' is updated, but full-text field is not (recommended to use REPLACE instead)", sWarning.cstr(), sUpdAttrName.cstr() );
}
break;
default:
sError.SetSprintf ( "attribute '%s' can not be updated (must be boolean, integer, bigint, float, timestamp, string, MVA or JSON)", sUpdAttrName.cstr() );
return false;
}
bool bSrcMva = tCol.m_eAttrType==SPH_ATTR_UINT32SET || tCol.m_eAttrType==SPH_ATTR_INT64SET || tCol.m_eAttrType==SPH_ATTR_FLOAT_VECTOR;
bool bDstMva = tUpdAttr.m_eType==SPH_ATTR_UINT32SET || tUpdAttr.m_eType==SPH_ATTR_INT64SET || tUpdAttr.m_eType==SPH_ATTR_FLOAT_VECTOR;
if ( bSrcMva!=bDstMva )
{
sError.SetSprintf ( "attribute '%s' MVA flag mismatch", sUpdAttrName.cstr() );
return false;
}
if( tCol.m_eAttrType==SPH_ATTR_UINT32SET && tUpdAttr.m_eType==SPH_ATTR_INT64SET )
{
sError.SetSprintf ( "attribute '%s' MVA bits (dst=%d, src=%d) mismatch", sUpdAttrName.cstr(), tCol.m_eAttrType, tUpdAttr.m_eType );
return false;
}
if( ( tCol.m_eAttrType==SPH_ATTR_UINT32SET || tCol.m_eAttrType==SPH_ATTR_INT64SET ) && tUpdAttr.m_eType==SPH_ATTR_FLOAT_VECTOR )
{
sError.SetSprintf ( "can't update MVA attribute '%s' bits with float vector value", sUpdAttrName.cstr() );
return false;
}
if ( tCol.IsColumnar() )
{
sError.SetSprintf ( "unable to update columnar attribute '%s'", sUpdAttrName.cstr() );
return false;
}
if ( tCol.IsIndexedKNN() && !( tUpd.m_bRebuildEmbeddings && tCol.m_eAttrType==SPH_ATTR_FLOAT_VECTOR && tUpdAttr.m_eType==SPH_ATTR_FLOAT_VECTOR ) )
{
sError.SetSprintf ( "unable to update attribute '%s' that has a KNN index", sUpdAttrName.cstr() );
return false;
}
}
return true;
}
static void IncUpdatePoolPos ( const CSphAttrUpdate & tUpdate, int iAttr, int & iPos )
{
switch ( tUpdate.m_dAttributes[iAttr].m_eType )
{
case SPH_ATTR_UINT32SET:
case SPH_ATTR_INT64SET:
case SPH_ATTR_FLOAT_VECTOR:
iPos += tUpdate.m_dPool[iPos] + 1;
break;
case SPH_ATTR_STRING:
case SPH_ATTR_BIGINT:
iPos += 2;
break;
default:
iPos += 1;
break;
}
}
void UpdateContext_t::PrepareListOfUpdatedAttributes ( CSphString & sError )
{
int iPoolPos = 0;
const auto & tUpd = *m_tUpd.m_pUpdate;
ARRAY_FOREACH ( iAttr, tUpd.m_dAttributes )
{
const CSphString & sUpdAttrName = tUpd.m_dAttributes[iAttr].m_sName;
ESphAttr eUpdAttrType = tUpd.m_dAttributes[iAttr].m_eType;
UpdatedAttribute_t & tUpdAttr = m_dUpdatedAttrs[iAttr];
int iUpdAttrId = m_tSchema.GetAttrIndex ( sUpdAttrName.cstr() );
if ( iUpdAttrId<0 )
{
CSphString sJsonCol;
if ( sphJsonNameSplit ( sUpdAttrName.cstr(), nullptr, &sJsonCol ) )
{
iUpdAttrId = m_tSchema.GetAttrIndex ( sJsonCol.cstr() );
if ( iUpdAttrId>=0 )
{
ExprParseArgs_t tExprArgs;
tUpdAttr.m_pExpr = sphExprParse ( sUpdAttrName.cstr(), m_tSchema, sError, tExprArgs );
}
}
}
if ( iUpdAttrId>=0 )
{
const CSphColumnInfo & tCol = m_tSchema.GetAttr(iUpdAttrId);
switch ( tCol.m_eAttrType )
{
case SPH_ATTR_FLOAT:
if ( eUpdAttrType==SPH_ATTR_BIGINT )
tUpdAttr.m_eConversion = CONVERSION_BIGINT2FLOAT;
break;
case SPH_ATTR_BIGINT:
if ( eUpdAttrType==SPH_ATTR_FLOAT )
tUpdAttr.m_eConversion = CONVERSION_FLOAT2BIGINT;
break;
default:
break;
}
tUpdAttr.m_eAttrType = tCol.m_eAttrType;
tUpdAttr.m_tLocator = tCol.m_tLocator;
tUpdAttr.m_pHistogram = m_pHistograms ? m_pHistograms->Get(tCol.m_sName) : nullptr;
tUpdAttr.m_bExisting = true;
tUpdAttr.m_iSchemaAttr = iUpdAttrId;
m_dSchemaUpdateMask.BitSet(iUpdAttrId);
m_bBlobUpdate |= sphIsBlobAttr(tCol);
}
else
{
assert ( tUpd.m_bIgnoreNonexistent ); // should be handled by Update_CheckAttributes
IncUpdatePoolPos ( tUpd, iAttr, iPoolPos );
continue;
}
// this is a hack
// Query parser tries to detect an attribute type. And this is wrong because, we should
// take attribute type from schema. Probably we'll rewrite updates in future but
// for now this fix just works.
// Fix cases like UPDATE float_attr=1 WHERE id=1;
assert ( iUpdAttrId>=0 );
if ( eUpdAttrType==SPH_ATTR_INTEGER && m_tSchema.GetAttr(iUpdAttrId).m_eAttrType==SPH_ATTR_FLOAT )
{
assert ( tUpd.m_dRowOffset.IsEmpty() ); // fixme! Now we don't fixup more then 1 value
const_cast<CSphAttrUpdate &>(tUpd).m_dAttributes[iAttr].m_eType = SPH_ATTR_FLOAT;
const_cast<CSphAttrUpdate &>(tUpd).m_dPool[iPoolPos] = sphF2DW ( (float)tUpd.m_dPool[iPoolPos] );
}
IncUpdatePoolPos ( tUpd, iAttr, iPoolPos );
}
}
static bool FitsInplaceJsonUpdate ( const UpdateContext_t & tCtx, int iAttr )
{
// only json fields and no strings (strings go as full json updates)
return tCtx.m_dUpdatedAttrs[iAttr].m_eAttrType==SPH_ATTR_JSON && tCtx.m_tUpd.m_pUpdate->m_dAttributes[iAttr].m_eType!=SPH_ATTR_STRING;
}
bool IndexSegment_c::Update_InplaceJson ( const RowsToUpdate_t& dRows, UpdateContext_t & tCtx, CSphString & sError, bool bDryRun )
{
const auto& tUpd = *tCtx.m_tUpd.m_pUpdate;
for ( const auto & tRow : dRows )
{
int iUpd = tRow.m_iIdx;
auto pDocinfo = tCtx.GetDocinfo ( tRow.m_tRow );
int iPos = tUpd.GetRowOffset ( iUpd );
ARRAY_CONSTFOREACH ( i, tUpd.m_dAttributes )
{
if ( !FitsInplaceJsonUpdate ( tCtx, i ) || !tCtx.m_dUpdatedAttrs[i].m_bExisting )
{
IncUpdatePoolPos ( tUpd, i, iPos );
continue;
}
ESphAttr eAttr = tUpd.m_dAttributes[i].m_eType;
bool bBigint = eAttr==SPH_ATTR_BIGINT;
bool bDouble = eAttr==SPH_ATTR_FLOAT;
ESphJsonType eType = bDouble ? JSON_DOUBLE : ( bBigint ? JSON_INT64 : JSON_INT32 );
SphAttr_t uValue = bDouble
? sphD2QW ( (double)sphDW2F ( tUpd.m_dPool[iPos] ) )
: ( bBigint ? MVA_UPSIZE ( &tUpd.m_dPool[iPos] ) : tUpd.m_dPool[iPos] );
if ( sphJsonInplaceUpdate ( eType, uValue, tCtx.m_dUpdatedAttrs[i].m_pExpr, tCtx.m_pBlobPool, pDocinfo, !bDryRun ) )
{
assert ( tCtx.m_dUpdatedAttrs[i].m_iSchemaAttr>=0 );
tCtx.m_tUpd.MarkUpdated ( iUpd );
tCtx.m_uUpdateMask |= ATTRS_BLOB_UPDATED;
// reset update bit to copy partial updated JSON into new blob
tCtx.m_dSchemaUpdateMask.BitClear ( tCtx.m_dUpdatedAttrs[i].m_iSchemaAttr );
} else
{
if ( bDryRun )
{
sError.SetSprintf ( "attribute '%s' can not be updated (not found or incompatible types)", tUpd.m_dAttributes[i].m_sName.cstr() );
return false;
} else
++tCtx.m_iJsonWarnings;
}
IncUpdatePoolPos ( tUpd, i, iPos );
}
}
return true;
}
bool IndexSegment_c::Update_Blobs ( const RowsToUpdate_t& dRows, UpdateContext_t & tCtx, bool & bCritical, CSphString & sError )
{
const auto & tUpd = *tCtx.m_tUpd.m_pUpdate;
// any blobs supplied in the update?
if ( !tCtx.m_bBlobUpdate )
return true;
// create a remap from attribute id in UPDATE to blob attr id
CSphVector<int> dRemap ( tUpd.m_dAttributes.GetLength() );
dRemap.Fill(-1);
CSphVector<int> dBlobAttrIds;
bool bNeedBlobBuilder = false;
int iBlobAttrId = 0;
for ( int i = 0, iAttrs = tCtx.m_tSchema.GetAttrsCount (); i < iAttrs; ++i )
{
const CSphColumnInfo & tAttr = tCtx.m_tSchema.GetAttr(i);
if ( sphIsBlobAttr(tAttr) )
{
dBlobAttrIds.Add(i);
ARRAY_CONSTFOREACH ( iUpd, tUpd.m_dAttributes )
{
const TypedAttribute_t & tTypedAttr = tUpd.m_dAttributes[iUpd];
if ( sphIsBlobAttr ( tTypedAttr.m_eType ) && tAttr.m_sName==tTypedAttr.m_sName )
{
dRemap[iUpd] = iBlobAttrId;
bNeedBlobBuilder = true;
}
}
++iBlobAttrId;
}
}
if ( !bNeedBlobBuilder )
return true;
CSphTightVector<BYTE> tBlobPool;
std::unique_ptr<BlobRowBuilder_i> pBlobRowBuilder = sphCreateBlobRowBuilderUpdate ( tCtx.m_tSchema, tUpd.m_dAttributes, tBlobPool, tCtx.m_dSchemaUpdateMask );
const CSphColumnInfo * pBlobLocator = tCtx.m_tSchema.GetAttr ( sphGetBlobLocatorName() );
for ( const auto & tRow : dRows )
{
int iUpd = tRow.m_iIdx;
auto pDocinfo = tCtx.GetDocinfo ( tRow.m_tRow );
tBlobPool.Resize(0);
ARRAY_CONSTFOREACH ( iBlobId, dBlobAttrIds )
{
int iCol = dBlobAttrIds[iBlobId];
if ( tCtx.m_dSchemaUpdateMask.BitGet(iCol) )
continue;
const CSphColumnInfo & tAttr = tCtx.m_tSchema.GetAttr(iCol);
int iLengthBytes = 0;
const BYTE* pData = sphGetBlobAttr ( pDocinfo, tAttr.m_tLocator, tCtx.m_pBlobPool, iLengthBytes );
BlobAttrInput_e eInput = BlobAttrInput_e::RAW_BYTES;
if ( tAttr.m_eAttrType==SPH_ATTR_UINT32SET || tAttr.m_eAttrType==SPH_ATTR_FLOAT_VECTOR )
eInput = BlobAttrInput_e::MVA_DWORD;
else if ( tAttr.m_eAttrType==SPH_ATTR_INT64SET )
eInput = BlobAttrInput_e::MVA_INT64;
if ( !pBlobRowBuilder->SetAttr ( iBlobId, pData, iLengthBytes, eInput, sError ) )
return false;
}
int iPos = tUpd.GetRowOffset ( iUpd );
ARRAY_CONSTFOREACH ( iCol, tUpd.m_dAttributes )
{
ESphAttr eAttr = tUpd.m_dAttributes[iCol].m_eType;
if ( !sphIsBlobAttr(eAttr) || FitsInplaceJsonUpdate ( tCtx, iCol ) || !tCtx.m_dUpdatedAttrs[iCol].m_bExisting )
{
IncUpdatePoolPos ( tUpd, iCol, iPos );
continue;