Using the GAE search API is it possible to search for a partial match?
I'm trying to create autocomplete functionality where the term would be a partial word. eg.
> b
> bui
> build
would all return "building".
How is this possible with GAE?
Though LIKE statement (partial match) is not supported in Full Text Search, but you could hack around it.
First, tokenize the data string for all possible substrings (hello = h, he, hel, lo, etc.)
def tokenize_autocomplete(phrase):
a = []
for word in phrase.split():
j = 1
while True:
for i in range(len(word) - j + 1):
a.append(word[i:i + j])
if j == len(word):
break
j += 1
return a
Build an index + document (Search API) using the tokenized strings
index = search.Index(name='item_autocomplete')
for item in items: # item = ndb.model
name = ','.join(tokenize_autocomplete(item.name))
document = search.Document(
doc_id=item.key.urlsafe(),
fields=[search.TextField(name='name', value=name)])
index.put(document)
Perform search, and walah!
results = search.Index(name="item_autocomplete").search("name:elo")
https://code.luasoftware.com/tutorials/google-app-engine/partial-search-on-gae-with-search-api/
just like @Desmond Lua answer, but with different tokenize function:
def tokenize(word): token=[] words = word.split(' ') for word in words: for i in range(len(word)): if i==0: continue w = word[i] if i==1: token+=[word[0]+w] continue token+=[token[-1:][0]+w] return ",".join(token)
it will parse hello world
as he,hel,hell,hello,wo,wor,worl,world
.
it's good for light autocomplete purpose
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With