2012-10-15 96 views
12

使用GAE search API可以搜索部分匹配嗎?部分匹配GAE搜索API

我試圖創建自動完成功能,其中的術語將是一個部分詞。例如。

> b
>裴
>打造

將全部迴歸 「建築」。

這對GAE來說可能如何?

回答

27

雖然LIKE語句(部分匹配)在全文搜索中不受支持,但您可以繞過它。

首先,令牌化所有可能的子用切分串的數據串(你好= H,他,HEL,滷味等)

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 

建立索引+文檔(搜索API)

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) 

執行搜索,然後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/

+0

這種運作良好。我設法修改了Ferris的search.index函數來自動標記所有文本字段(一行更改),並且它「正常工作」。只是不要嘗試直接從搜索結果中向用戶顯示該字段;) –

+1

我還添加了'name.lower()',因爲我有一些俄語的奇怪問題:如果令牌以大寫字母開頭我無法找到這樣的標記。 –

+8

友情提示:短語是「voila!」 –

0

我有預輸入控制同樣的問題,我的解決方法是解析字符串小部分:

name='hello world' 
name_search = ' '.join([name[:i] for i in xrange(2, len(name)+1)]) 
print name_search; 
# -> he hel hell hello hello hello w hello wo hello wor hello worl hello world 

希望這有助於

2

就像@Desmond Lua的答案,但具有不同的標記化功能:

 
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) 

它將解析hello world作爲he,hel,hell,hello,wo,wor,worl,world

它的良好的光線自動完成目的

0

我的版本優化:不重複令牌

def tokenization(text): 
    a = [] 
    min = 3 
    words = text.split() 
    for word in words: 
     if len(word) > min: 
      for i in range(min, len(word)): 
       token = word[0:i] 
       if token not in a: 
        a.append(token) 
    return a 
+0

請添加更多關於您發佈的答案的說明先生。 –