├── .gitignore
├── LICENSE
├── README.md
├── TreeIndex.cpp
├── TreeIndex.h
├── en.txt
├── main.cpp
├── noderank.png
└── treesearch.png
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled Object files
2 | *.slo
3 | *.lo
4 | *.o
5 | *.obj
6 |
7 | # Precompiled Headers
8 | *.gch
9 | *.pch
10 |
11 | # Compiled Dynamic libraries
12 | *.so
13 | *.dylib
14 | *.dll
15 |
16 | # Fortran module files
17 | *.mod
18 |
19 | # Compiled Static libraries
20 | *.lai
21 | *.la
22 | *.a
23 | *.lib
24 |
25 | # Executables
26 | *.exe
27 | *.out
28 | *.app
29 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
167 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Eli-Index : Ranked Prefix Search for Large Data on External Memory
2 | Previously I wrote (https://github.com/maksimpiriyev/Search-As-You-Type-Index-master) about fast prefix search for ~10,000 key-value pairs designed for mobile.Now,Eli-Index designed to handle more than 1,000,000 key-value pairs,make fast prefix search on them,and furthermore bring the most ranked one from index.It stores index and data at the same time on external memory not in RAM (caches the nodes while it needs)
3 |
4 |
5 | Most of the prefix search indices are designed for server side use,they store index in the RAM so that has intialization latency which prenvents opening application more faster in mobile(using threads also slows down the main thread).Eli-Index is designed to overcome this problem.
6 | Eli-Index is designed over AVL Tree,Segmented Tree and with Heap.Its nodes has the features of both AVL Tree and Segmented Tree.It makes prefix search over AVL Tree ,and gets the result list in sorted order while iterating on the nodes of segmented tree with the help of heap. It might also be the first AVL Tree implemented for string prefix search as I couldn't find any paper or implementation that use AVL Tree for string Prefix Search. Eli-Index has preferred to use AVL Tree instead of Trie Index because if Trie Index is implemented in External Memory,Either it is fast and uses more memory or it is slower because of more random file access.
7 |
8 | ### Class structure:
9 | ```c++
10 | class TreeIndex{
11 |
12 | public:
13 | TreeIndex(const string fileName);
14 | void save();
15 | long size();
16 | vector > search(wstring txt, int maxCount = 100);
17 | vector searchOnlyString(wstring txt, int maxCount = 100);
18 | tuple* find(wstring txt);
19 | void add(wstring txt, long statCount = 1/*rank*/,long value = 0);
20 | void loadNgram(string fileName, int ngram);
21 | void loadTopWords(string fileName,int maxCount=-1);
22 | bool isExist(wstring s);
23 | void setText(Node* n, wstring txt);
24 | void clearCache();
25 | int cacheSize();
26 | int treeHeight();
27 | };
28 | ```
29 | Its usage :
30 | ```c++
31 | TreeIndex xx("index_en.tf");
32 | cout << xx.treeHeight() << endl;
33 | xx.add(L"pretend");
34 | xx.add(L"predict",1);
35 | xx.add(L"prediction",2,1);
36 | auto xff = xx.search(L"pre",100);
37 | for (size_t j = 0; j < xff.size(); j++)
38 | {
39 | wcout << std::get<1>(xff[j]) << endl;
40 | }
41 |
42 | ```
43 |
44 | ### Prefix Search with AVL Tree
45 | Note that AVL Tree is the same as it was with same operations,but Prefix Search on AVL Tree is little bit different than the regular search on AVL Tree.Lets say we are searching the prefix P.We always compare the prefix of the text in the node with length |P|.
46 |
47 | > * If node N is greater than the prefix then its right nodes do not contain that prefix.
48 | > * If node N is smaller than the prefix then its left nodes do not contain that prefix.
49 | > * The case that left node is smaller than P and right node is greater than P might exists only at the node itself or (either in left subtree or in right subtree),but not left and right subtree at the same time.This is why the complexity is logN not 2^N
50 | 
51 |
52 |
53 | ### Top K Ranks with Segmented Tree
54 | Segmented Tree is well known structure to find the min-max values in any tree. Eli-Index iterates between top min-max values using heap.
55 |
56 | > * Adding (K+1)th element to the heap and removing the least element guarantees that heap has the top K elements.
57 | 
58 |
59 | ### Insert Comlexity
60 | Insert complexity is as same as the AVL tree O(logN)
61 |
62 | ### Search Complexity for top K words
63 | Segmented Tree has the O(logN) complexity for finding the node with maximum rank value,using heap and finding next K-1 complexity brings extra O(lgK*lglgN) overhead.
64 | > Total Complexity: O(K* lgK* lgN* lglgN) .
65 |
66 | ### Compilation
67 | It is written in C++11.
68 | > g++ -Ofast -std=c++11 -o prog main.cpp TreeFile.cpp
69 |
70 | ### Eli-Index vs SQL
71 | Note that nowadays most of the databases have prefix search with their full-text search functionality.Lets say you have more than 1,000,000 words and 100,000 of them starts with "a*" and you want search all of them ordered by their rank.This time Eli-Index and SQL will have very similar performance results.But If you search top 10 ranked(user-defined) results from these 100,000 words then Eli-Index will drammatically beat SQL,because SQL is abstract it retrieves and then sorts for column and gets top results, instead El-Index finds top nodes first by default
72 |
73 | ### OS Cache and Initial Latency
74 | Some Operating Systems has the policy to cache whole file at first acess before you do any operation on it (OS-wide first access),and it brings extra latency in the first operation,but meanwhile makes faster the other operations.But, you can use fadvise,fcntrl etc to disable cache or tell the read pattern is random.
75 |
76 | ### Apps that use this index
77 | Typing auto-complete for mac : http://elithetyper.com
78 |
79 | by Maksim Piriyev
80 |
--------------------------------------------------------------------------------
/TreeIndex.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 | #include "TreeIndex.h"
10 | #include
11 | #include
12 | #include
13 | using namespace std;
14 | #define MAXNODECOUNT 40
15 | #define COUNTTHRESHOLD 4000000
16 |
17 | static map dictCharToIndex = { { ' ', 0 }, { 'a', 1 }, { 'b', 2 }, { 'c', 3 }, { 'd', 4 }, { 'e', 5 }, { 'f', 6 }, { 'g', 7 }, { 'h', 8 }, { 'i', 9 },
18 | { 'j', 10 }, { 'k', 11 }, { 'l', 12 }, { 'm', 13 }, { 'n', 14 }, { 'o', 15 }, { 'p', 16 }, { 'q', 17 }, { 'r', 18 }, { 's', 19 },
19 | { 't', 20 }, { 'u', 21 }, { 'v', 22 }, { 'w', 23 }, { 'x', 24 }, { 'y', 25 }, { 'z', 26 }, { '.', 27 }, { '-', 28 }, { 's', 29 }
20 |
21 | };
22 | static map dictIndexToChar = { { 0,' ' }, { 1,'a' }, { 2,'b' }, { 3,'c'}, { 4,'d' }, { 5,'e' }, { 6,'f' }, { 7,'g' }, {8, 'h' }, { 9,'i' },
23 | { 10,'j' }, { 11,'k' }, { 12,'l' }, { 13,'m' }, { 14,'n'}, { 15,'o' }, { 16,'p' }, { 17,'q' }, { 18,'r'}, { 19,'s' },
24 | { 20,'t' }, { 21,'u' }, { 22,'v' }, { 23,'w' }, { 24,'x'}, { 25,'y' }, { 26,'z' }, { 27,'.' }, { 28,'-'}, { 29,'s' }
25 |
26 | };
27 |
28 | namespace Index{
29 |
30 | typedef unsigned int uint;
31 | typedef unsigned short word;
32 | typedef unsigned char byte;
33 |
34 | int UTF16to8(const wchar_t* w, char* s ) {
35 | uint c;
36 | word* p = (word*)w;
37 | byte* q = (byte*)s; byte* q0 = q;
38 | while( 1 ) {
39 | c = *p++;
40 | if( c==0 ) break;
41 | if( c<0x080 ) *q++ = c; else
42 | if( c<0x800 ) *q++ = 0xC0+(c>>6), *q++ = 0x80+(c&63); else
43 | *q++ = 0xE0+(c>>12), *q++ = 0x80+((c>>6)&63), *q++ = 0x80+(c&63);
44 | }
45 | *q = 0;
46 | return q-q0;
47 | }
48 |
49 | Node::Node(){
50 | this->statCount = this->maxStatCount = this->nodeHeight = 0;
51 | this->textIndex = -1;
52 | this->text = NULL;
53 | this->leftNodeId = this->rightNodeId = -1;
54 | this->parentTextNodeId=-1;
55 | }
56 |
57 | TreeIndex::TreeIndex(const string fileName){
58 | this->fileName = fileName;
59 | // file=fopen( "C:\\Users\\Maksim Piriyev\\index_en.tf", "rb+");
60 |
61 | const char* cfileName=fileName.c_str();
62 | printf("%s",cfileName);
63 | file = fopen( cfileName, "rb+");
64 | wordFile = fopen( (fileName + ".w").c_str(), "rb+");
65 | // int fd= (int)file;
66 | //fcntl(F_NOCACHE)
67 | cout<file != NULL) fclose(this->file);
100 | if (this->wordFile != NULL) fclose(this->wordFile);
101 | cache.clear();
102 | }
103 | void TreeIndex::loadTopWords(string fileName,int maxCount){
104 | wifstream in(fileName);
105 | wstring word;
106 | int counter = 1;
107 | in.imbue(std::locale(std::locale::classic(), new std::codecvt_utf8));
108 |
109 | //maxCount = 100000;
110 |
111 | vector lst;
112 | while (in >> word && counter<=maxCount){
113 | lst.push_back(word);
114 | ++counter;
115 | }
116 | cout << "readed " <0 && i % 3000 == 0){
132 | cout << i << endl;
133 | // es = ensureStats();
134 | //
135 | // if (!es){
136 | // cout << "problem:" << i << endl;
137 | // return;
138 | // }
139 | // save();
140 | // clearCache();
141 | }
142 | }
143 | save();
144 | clearCache();
145 | cout<<"finished"<));
160 |
161 | int statCount;
162 | wstring words[10];
163 | int counter = 0;
164 | vector stats;
165 | vector lst;
166 | while (in >> statCount){
167 | wstring rslt;
168 | for (int i = 0; i < ngram; i++)
169 | {
170 | in >> words[i];
171 | if (i>0) rslt += L" ";
172 | rslt += words[i];
173 | }
174 | stats.push_back(statCount);
175 | lst.push_back(rslt);
176 |
177 |
178 | counter++;
179 | if (counter == 1266){
180 | int ff = 0;
181 | cout << "AS"<add(lst[i], stats[i]);
188 | }
189 | save();
190 | clearCache();
191 | cout << counter << endl;
192 | cout << treeHeight() << endl;
193 | stats.clear();
194 | lst.clear();
195 |
196 | }
197 | }
198 | for (size_t i = 0; i < stats.size(); i++)
199 | {
200 | this->add(lst[i], stats[i]);
201 | }
202 | this->save();
203 | this->clearCache();
204 | return;
205 | int j = stats.size() / 2;
206 | for (size_t i = 0; (i + j) = 0; i++)
207 | {
208 | this->add(lst[j + i], stats[j + i]);
209 | if (i>0)
210 | this->add(lst[j - i], stats[j - i]);
211 | counter++;
212 | if (counter % 1000 == 0)
213 | this->save();
214 | }
215 |
216 | }
217 | bool TreeIndex::ensureStats(int node,long stat){
218 | if (node < 0) return true;
219 | auto n = this->get(node);
220 | if (node == 0) stat = n->maxStatCount;
221 | if (n->maxStatCount < n->statCount || stat < n->maxStatCount) return false;
222 | bool r = ensureStats(n->leftNodeId,stat);
223 | bool r2 = ensureStats(n->rightNodeId,stat);
224 | bool r4 = false;
225 | return r&&r2;
226 | return ensureStats(n->leftNodeId,stat) && ensureStats(n->rightNodeId,stat);
227 | //return true;
228 | }
229 | void TreeIndex::clearCache(){
230 | for (auto t = cache.begin(); t != cache.end(); t++)
231 | {
232 | auto i = *t;
233 | if(i.second->text!=NULL)
234 | delete[] i.second->text;
235 | }
236 | cache.clear();
237 | }
238 | int TreeIndex::cacheSize(){
239 |
240 | return cache.size();
241 | }
242 | Node* TreeIndex::get(long nodeId){
243 | if (nodeId < 0) return NULL;
244 | if (cache.count(nodeId) > 0) return cache[nodeId];
245 |
246 | //return NULL;
247 | long sz = this->size();
248 | if (sz <= nodeId) return NULL;
249 |
250 |
251 | Node* n = new Node();
252 |
253 | fseek(this->file, sizeof(Node)*nodeId, SEEK_SET);
254 | fread(n, sizeof(Node), 1, this->file);
255 | n->text = new wchar_t[n->textCount + 1];
256 | fseek(this->wordFile, n->textIndex, SEEK_SET);
257 | fread(n->text, sizeof(wchar_t), n->textCount + 1, this->wordFile);
258 | cache[nodeId] = n;
259 | return n;
260 | }
261 |
262 | void TreeIndex::save(){
263 | for (auto t = saveQueue.begin(); t != saveQueue.end(); t++)
264 | {
265 | long nodeId = *t;
266 | Node* n = cache[nodeId];
267 | if (n->textIndex == -1){
268 | fseek(this->wordFile, 0, SEEK_END);
269 | n->textIndex = ftell(wordFile);
270 | fwrite(n->text, sizeof(wchar_t), n->textCount + 1, this->wordFile);
271 | }
272 | fseek(this->file, sizeof(Node)*nodeId, SEEK_SET);
273 | fwrite(n, sizeof(Node), 1, this->file);
274 | }
275 | fflush(file);
276 | fflush(wordFile);
277 |
278 | saveQueue.clear();
279 | // cache.clear();
280 | }
281 | int indexOf(int ch){
282 |
283 | return dictCharToIndex[ch];
284 | }
285 | wchar_t charFromIndex(int i){
286 | return dictIndexToChar[i];
287 | }
288 | bool hasPrefix(wstring txt, wstring prefix){
289 | if (txt.length() < prefix.length()) return false;
290 |
291 | return prefix == txt.substr(0, prefix.length());
292 | }
293 | void TreeIndex::setText(Node* n, wstring txt){
294 | n->text = new wchar_t[txt.length() + 1];
295 | wcscpy(n->text, txt.c_str());
296 | n->textCount = txt.length();
297 | }
298 | void TreeIndex::add(wstring txt, long statCount,long value){
299 | //txt = txt.toLower();
300 | long nodeId = 0, subNodeId = -1;
301 | Node* n = this->get(nodeId);
302 | if (n == NULL) {
303 | nodeId = newNode();
304 | n = this->get(nodeId);
305 | }
306 |
307 | vector l = { nodeId };
308 |
309 | bool did = true;
310 | while (did){
311 | did = false;
312 | if (n->text != NULL && wstring(n->text) == txt){
313 | //if (n->statCount < COUNTTHRESHOLD) n->statCount = COUNTTHRESHOLD;
314 | n->statCount += statCount;
315 | n->value = value;
316 | saveQueue.insert(nodeId);
317 | updateMaxStatCounts(l);
318 | return;
319 | }
320 | if (n->leftNodeId > 0 && wstring(n->text) > txt){
321 | nodeId = n->leftNodeId;
322 | n = this->get(n->leftNodeId);
323 | l.push_back(nodeId);
324 | did = true;
325 | }
326 | else if (n->rightNodeId > 0 && wstring(n->text) <= txt){
327 | nodeId = n->rightNodeId;
328 | n = this->get(n->rightNodeId);
329 | l.push_back(nodeId);
330 | did = true;
331 | }
332 | }
333 | if (n->text == NULL){
334 | setText(n, txt);
335 | saveQueue.insert(nodeId);
336 | }
337 | else if (n->leftNodeId < 0 && wstring(n->text) >= txt){
338 | saveQueue.insert(nodeId);
339 |
340 | long newNodeId = newNode();
341 | n->leftNodeId = newNodeId;
342 | n = this->get(newNodeId);
343 | setText(n, txt);
344 | l.push_back(newNodeId);
345 | }
346 | else if (n->rightNodeId < 0 && wstring(n->text) <= txt){
347 | saveQueue.insert(nodeId);
348 |
349 | long newNodeId = newNode();
350 | n->rightNodeId = newNodeId;
351 | n = this->get(newNodeId);
352 | setText(n, txt);
353 | l.push_back(newNodeId);
354 |
355 | }
356 | n->statCount = n->maxStatCount = statCount;
357 | n->value = value;
358 |
359 | updateMaxStatCounts(l);
360 | }
361 | int charSize(){
362 |
363 | return dictCharToIndex.size();
364 | }
365 |
366 | void TreeIndex::addSave(wstring txt, long statCount){
367 | add(txt,statCount);
368 | save();
369 | }
370 | void TreeIndex::updateMaxStatCounts(vector& nodes){
371 | bool firsttime = true;
372 | long maxStatCount = 0;
373 | bool did = true;
374 | for (int i = nodes.size() - 1; i >= 0 && did; i--)
375 | {
376 | //did = false;
377 | Node* n = this->get(nodes[i]);
378 | if (firsttime){
379 | firsttime = false;
380 | if (n->maxStatCount < n->statCount){
381 | n->maxStatCount = n->statCount;
382 | saveQueue.insert(nodes[i]);
383 | }
384 | // maxStatCount = n->maxStatCount;
385 | did = true;
386 | balanceNode(nodes[i]);
387 | continue;
388 | }
389 | /*if (n->maxStatCount < maxStatCount){
390 | n->maxStatCount = maxStatCount;
391 | saveQueue.insert(nodes[i]);
392 | did = true;
393 | }*/
394 | //maxStatCount = max(maxStatCount, n->maxStatCount);
395 | did |= balanceNode(nodes[i]);
396 |
397 | }
398 | }
399 | //void TreeIndex::incrementUsage(wstring txt, int statCount){
400 | // this->add(txt, statCount);
401 | //}
402 | bool TreeIndex::isExist(wstring txt){
403 | auto r = this->search(txt);
404 | if (r.size() > 0 && std::get<1>(r[0]) == txt) return true;
405 | return false;
406 | }
407 | int TreeIndex::treeHeight(){
408 | return nodeHeight(0);
409 | }
410 | int TreeIndex::nodeHeight(long nodeId){
411 | Node* n = this->get(nodeId);
412 | return n == NULL ? 0 : n->nodeHeight;
413 | }
414 | int TreeIndex::updateNodeHeight(long nodeId){
415 | Node* n = this->get(nodeId);
416 | if (n == NULL) return 0;
417 | Node* l = n->leftNodeId < 0 ? NULL : this->get(n->leftNodeId);
418 | Node* r = n->rightNodeId < 0 ? NULL : this->get(n->rightNodeId);
419 | int h = max(l == NULL ? 0 : l->nodeHeight, r == NULL ? 0 : r->nodeHeight) + 1;
420 | if (h != n->nodeHeight) saveQueue.insert(nodeId);
421 |
422 | return n->nodeHeight = h;
423 | }
424 | int TreeIndex::updateNodeStat(long nodeId){
425 | Node* n = this->get(nodeId);
426 | if (n == NULL) return 0;
427 | Node* l = n->leftNodeId < 0 ? NULL : this->get(n->leftNodeId);
428 | Node* r = n->rightNodeId < 0 ? NULL : this->get(n->rightNodeId);
429 | long st = max(n->statCount, max(l == NULL ? n->statCount : l->maxStatCount, r == NULL ? n->statCount : r->maxStatCount));
430 | if (st != n->maxStatCount) saveQueue.insert(nodeId);
431 |
432 | return n->maxStatCount = st;
433 | }
434 |
435 | int TreeIndex::balanceFactor(long nodeId){
436 | Node* n = this->get(nodeId);
437 | if (n == NULL) return 0;
438 | int lh = (n->leftNodeId == 0 ? 0 : nodeHeight(n->leftNodeId)), rh = n->rightNodeId == 0 ? 0 : nodeHeight(n->rightNodeId);
439 | return lh - rh;
440 | }
441 |
442 | bool TreeIndex::balanceNode(long nodeId){
443 | Node* n = this->get(nodeId);
444 | if (n == NULL) return false;
445 | int bf = balanceFactor(nodeId);
446 | bool did = false;
447 | if (bf <= -2){
448 | int lbf = balanceFactor(n->rightNodeId);
449 | if (lbf >= 1)
450 | rotateRight(n->rightNodeId);
451 | rotateLeft(nodeId);
452 | did = true;
453 | }
454 | else if (bf >= 2){
455 | int rbf = balanceFactor(n->leftNodeId);
456 | if (rbf <= -1)
457 | rotateLeft(n->leftNodeId);
458 | rotateRight(nodeId);
459 | did = true;
460 | }
461 | updateNodeHeight(nodeId);
462 | updateNodeStat(nodeId);
463 | return did;
464 | }
465 | void TreeIndex::rotateRight(long nodeId){
466 | Node* n = this->get(nodeId);
467 | int ln = n->leftNodeId;
468 | if (n == NULL || ln < 0) return;
469 | saveQueue.insert(nodeId);
470 | saveQueue.insert(ln);
471 |
472 | Node* l = this->get(n->leftNodeId);
473 | swap(*n, *l);
474 | l->leftNodeId = n->rightNodeId;
475 | n->rightNodeId = ln;
476 | updateNodeHeight(ln);
477 | updateNodeStat(ln);
478 | updateNodeHeight(nodeId);
479 | updateNodeStat(nodeId);
480 |
481 | }
482 |
483 | void TreeIndex::rotateLeft(long nodeId){
484 | Node* n = this->get(nodeId);
485 | int rn = n->rightNodeId;
486 | if (n == NULL || rn < 0) return;
487 | saveQueue.insert(nodeId);
488 | saveQueue.insert(rn);
489 |
490 | Node* r = this->get(n->rightNodeId);
491 | swap(*n, *r);
492 | r->rightNodeId = n->leftNodeId;
493 | n->leftNodeId = rn;
494 | updateNodeHeight(rn);
495 | updateNodeStat(rn);
496 | updateNodeHeight(nodeId);
497 | updateNodeStat(nodeId);
498 | }
499 | ///////////////////////
500 |
501 |
502 | bool treesort(tuple& p1, tuple& p2){
503 | return std::get<0>(p1) == std::get<0>(p2) ?
504 | std::get<1>(p1).length() < std::get<1>(p2).length() : (std::get<0>(p2) < std::get<0>(p1));
505 | }
506 | tuple* TreeIndex::find(wstring txt){
507 | long nodeId = 0;
508 | Node* n = this->get(nodeId);
509 | if (n == NULL)
510 | return NULL;
511 |
512 | bool did = true;
513 | while (did && n != NULL && (n->rightNodeId > 0 || n->leftNodeId > 0) ){
514 | did = false;
515 | if (wstring(n->text) == txt){
516 | return new tuple(n->statCount, txt,n->value);
517 | }
518 | if (n->leftNodeId > 0 && wstring(n->text) >= txt){
519 | n = this->get(nodeId = n->leftNodeId);
520 | did = true;
521 | }
522 | else if (n->rightNodeId > 0 && wstring(n->text) < txt){
523 | n = this->get(nodeId = n->rightNodeId);
524 | did = true;
525 | }
526 | }
527 | return NULL;
528 | }
529 | vector > TreeIndex::search(wstring txt, int maxCount){
530 | // std::transform(txt.begin(), txt.end(), txt.begin(), ::tolower);
531 |
532 | vector > rtn;
533 | long nodeId = 0;
534 | Node* n = this->get(nodeId);
535 | if (n == NULL)
536 | return rtn;
537 | wcout << txt << endl;
538 | bool did = true;
539 | while (did && n != NULL && (n->rightNodeId > 0 || n->leftNodeId > 0) && !hasPrefix(wstring(n->text), txt)){
540 | did = false;
541 | if (n->leftNodeId > 0 && wstring(n->text) >= txt){
542 | n = this->get(nodeId = n->leftNodeId);
543 | did = true;
544 | }
545 | else if (n->rightNodeId > 0 && wstring(n->text) < txt){
546 | n = this->get(nodeId = n->rightNodeId);
547 | did = true;
548 | }
549 | }
550 | if (!hasPrefix(wstring(n->text), txt)) return rtn;
551 |
552 | priority_queue > maxq;
553 | priority_queue > curq; // has the least stat value on top maxCount
554 |
555 | maxq.push(make_pair(n->maxStatCount, nodeId));
556 | while (!maxq.empty()){
557 | auto t = maxq.top();
558 | maxq.pop();
559 |
560 | n = this->get(t.second);
561 | curq.push(make_pair(-n->statCount, t.second));
562 | // cout << n->maxStatCount << " - " << n->statCount << " - " << -curq.top().first << endl;
563 |
564 | if (curq.size() >= maxCount && n->statCount <= -this->get(curq.top().second)->statCount){
565 | break;
566 | }
567 |
568 | while (curq.size() > maxCount) curq.pop();
569 |
570 | Node* nt = this->get(nodeId = n->leftNodeId);
571 | while (nt && !hasPrefix(wstring(nt->text), txt) ){
572 | nt = this->get(nodeId = nt->rightNodeId);
573 | }
574 | if (nt && hasPrefix(wstring(nt->text), txt))
575 | maxq.push(make_pair(nt->maxStatCount, nodeId));
576 |
577 | nt = this->get(nodeId = n->rightNodeId);
578 | while (nt && !hasPrefix(wstring(nt->text), txt) ){
579 | nt = this->get(nodeId = nt->leftNodeId);
580 | }
581 | if (nt && hasPrefix(wstring(nt->text), txt))
582 | maxq.push(make_pair(nt->maxStatCount, nodeId));
583 |
584 |
585 |
586 |
587 | }
588 | //popping the last item if exists
589 | while (curq.size() > maxCount) curq.pop();
590 |
591 | while (!curq.empty())
592 | {
593 | n = this->get(curq.top().second);
594 | curq.pop();
595 | rtn.insert(rtn.begin(),tuple(n->statCount, wstring(n->text), n->value));
596 | }
597 | //reverse(rtn.begin(), rtn.end());
598 |
599 | //sort(rtn.begin(), rtn.end(), treesort);
600 | cout << rtn.size() << endl;
601 | return rtn;
602 | }
603 | vector TreeIndex::searchOnlyString(wstring txt, int maxCount ){
604 | auto t=search(txt,maxCount);
605 | vector rtn;
606 | for (size_t i = 0; i < t.size(); i++)
607 | {
608 | rtn.push_back(std::get<1>(t[i]));
609 | }
610 | return rtn;
611 | }
612 |
613 | void TreeIndex::setDoubleKeys(vector& chars ){
614 | mapDoubleKeys.clear();
615 | for (int i=0; i > TreeIndex::searchDouble(wstring txt, int maxCount = 100){
622 | vector > rtn;
623 | long nodeId = 0;
624 | Node* n = this->get(nodeId);
625 | if (n == NULL)
626 | return rtn;
627 | wcout << txt << endl;
628 | bool did = true;
629 | while (did && n != NULL && (n->rightNodeId > 0 || n->leftNodeId > 0) && !hasPrefix(wstring(n->text), txt)){
630 | did = false;
631 | if (n->leftNodeId > 0 && wstring(n->text) >= txt){
632 | n = this->get(nodeId = n->leftNodeId);
633 | did = true;
634 | }
635 | else if (n->rightNodeId > 0 && wstring(n->text) < txt){
636 | n = this->get(nodeId = n->rightNodeId);
637 | did = true;
638 | }
639 | }
640 | if (!hasPrefix(wstring(n->text), txt)) return rtn;
641 |
642 | priority_queue > maxq;
643 | priority_queue > curq; // has the least stat value on top maxCount
644 |
645 | maxq.push(make_pair(n->maxStatCount, nodeId));
646 | while (!maxq.empty()){
647 | auto t = maxq.top();
648 | maxq.pop();
649 |
650 | n = this->get(t.second);
651 | curq.push(make_pair(-n->statCount, t.second));
652 | // cout << n->maxStatCount << " - " << n->statCount << " - " << -curq.top().first << endl;
653 |
654 | if (curq.size() >= maxCount && n->statCount <= -this->get(curq.top().second)->statCount){
655 | break;
656 | }
657 |
658 | while (curq.size() > maxCount) curq.pop();
659 |
660 | Node* nt = this->get(nodeId = n->leftNodeId);
661 | while (nt && !hasPrefix(wstring(nt->text), txt) ){
662 | nt = this->get(nodeId = nt->rightNodeId);
663 | }
664 | if (nt && hasPrefix(wstring(nt->text), txt))
665 | maxq.push(make_pair(nt->maxStatCount, nodeId));
666 |
667 | nt = this->get(nodeId = n->rightNodeId);
668 | while (nt && !hasPrefix(wstring(nt->text), txt) ){
669 | nt = this->get(nodeId = nt->leftNodeId);
670 | }
671 | if (nt && hasPrefix(wstring(nt->text), txt))
672 | maxq.push(make_pair(nt->maxStatCount, nodeId));
673 |
674 |
675 |
676 |
677 | }
678 | //popping the last item if exists
679 | while (curq.size() > maxCount) curq.pop();
680 |
681 | while (!curq.empty())
682 | {
683 | n = this->get(curq.top().second);
684 | curq.pop();
685 | rtn.insert(rtn.begin(),tuple(n->statCount, wstring(n->text), n->value));
686 | }
687 | //reverse(rtn.begin(), rtn.end());
688 |
689 | //sort(rtn.begin(), rtn.end(), treesort);
690 | cout << rtn.size() << endl;
691 | return rtn;
692 |
693 | }
694 | }
--------------------------------------------------------------------------------
/TreeIndex.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include