2016-12-15 269 views
0

我試圖提供搜索最終用戶的類型,因爲他們走哪個更像是sqlserver。我是能夠實現ES查詢給定的SQL場景:ngram通配符搜索彈性搜索

select * from table where name like '%peter tom%' and type != 'xyz 

在ES我使用NGRAM分詞器,以達到預期的效果:

PUT sample 
{ 
    "settings": { 
    "analysis": { 
     "analyzer": { 
     "my_ngram_analyzer": { 
      "tokenizer": "my_ngram_tokenizer" 
     } 
     }, 
     "tokenizer": { 
     "my_ngram_tokenizer": { 
      "type": "nGram", 
      "min_gram": "2", 
      "max_gram": "15" 
     } 
     } 
    } 
    }, 
    "mappings": { 
    "typename": { 
     "properties": { 
     "name": { 
      "type": "string", 
      "fields": { 
      "search": { 
       "type": "string", 
       "analyzer": "my_ngram_analyzer" 
      } 
      } 
     }, 
     "type": { 
      "type": "string", 
      "index": "not_analyzed" 
     } 
     } 
    } 
    } 
} 

{ 
    "query": { 
    "bool": { 
     "should": [ 
     { 
      "term": { 
      "name.search": "peter tom" 
      } 
     } 
     ], 
     "must_not": [ 
     { 
      "match": { 
      "type": "xyz" 
      } 
     }, 
     { 
      "match": { 
      "type": "abc" 
      } 
     } 
     ] 
    } 
    } 
} 

所以,如果我的文檔行像

name        type 
peter tomson      efg 
Peter tomson robert simson  efg 

上述查詢只顯示兩個文件,但當我嘗試輸入彼得sims或彼得simson它不返回第二個文件,除非我輸入彼得湯姆森羅伯特模擬人生或寵物呃湯姆森羅伯特辛普森。所以基本上我必須在彼得和辛普森之前輸入下面所有的單詞來獲得第二個文檔。有沒有什麼辦法獲得第二個文件的部分匹配。我可以使用查詢匹配和「AND」操作,但仍然在單詞的精確匹配。我正在尋找像彼得sims部分匹配應該給我第二行的文件。 感謝

回答

0

我找到了答案,查詢自己張貼的其他用戶進一步參考的解決方案:

{ 
    "settings": { 
     "analysis": { 
      "analyzer": { 
       "autocomplete": { 
        "tokenizer": "whitespace", 
        "filter": [ 
         "lowercase", 
         "autocomplete" 
        ] 
       }, 
       "autocomplete_search": { 
        "tokenizer": "whitespace", 
        "filter": [ 
         "lowercase" 
        ] 
       } 
      }, 
      "filter": { 
       "autocomplete": { 
        "type": "nGram", 
        "min_gram": 2, 
        "max_gram": 40 
       } 
      } 
     } 
    }, 
    "mappings": { 
     "doc": { 
      "properties": { 
       "title": { 
        "type": "string", 
        "analyzer": "autocomplete", 
        "search_analyzer": "autocomplete_search" 
       } 
      } 
     } 
    } 
} 

PUT my_index/doc/1 
{ 
    "title": "peter tomson" 
} 

PUT my_index/doc/2 
{ 
    "title": "Peter tomson robert simson" 
} 


GET my_index/doc/_search 
    { 
     "query": { 
     "match": { 
      "title": { 
      "query": "Pete sim", 
      "operator": "and" 
      } 
     } 
     } 
    } 
+0

感謝分享。幫助像我這樣的初學者! –