Elastic search 的 completion 搜索提示和模糊查询

921 阅读1分钟

想要使用 Elastic search 工具来实现搜索框的提示功能,可以按照本文的步骤来进行设置。

  1. 安装好 jieba 插件,如果有 ik 也可,但是相应的下面的 analyzer 作出相应的改变即可。

  2. 定义 mapping

      PUT games
      {
        "mappings": {
            "properties" : {
              "title" : {
                "type": "completion"
              }
            }
        }
      }
    
  3. 增加数据

      PUT /games/_doc/1
      {
        "title": "Nevermind"
      }
      PUT /games/_doc/2
      {
        "title": "Nirvana"
      }
    
  4. 查找

      POST games/_search?pretty
     {
         "suggest": {
             "song-suggest" : {
                 "prefix" : "nor",
                 "completion" : {
                     "field" : "title",
                     "fuzzy" : {
                         "fuzziness" : 2
                     }
                 }
             }
         }
     }
    
  5. 结果

     {
       "took" : 0,
       "timed_out" : false,
       "_shards" : {
         "total" : 1,
         "successful" : 1,
         "skipped" : 0,
         "failed" : 0
       },
       "hits" : {
         "total" : {
           "value" : 0,
           "relation" : "eq"
         },
         "max_score" : null,
         "hits" : [ ]
       },
       "suggest" : {
         "song-suggest" : [
           {
             "text" : "nor",
             "offset" : 0,
             "length" : 3,
             "options" : [
               {
                 "text" : "Nevermind",
                 "_index" : "games",
                 "_type" : "_doc",
                 "_id" : "1",
                 "_score" : 1.0,
                 "_source" : {
                   "title" : "Nevermind"
                 }
               },
               {
                 "text" : "Nirvana",
                 "_index" : "games",
                 "_type" : "_doc",
                 "_id" : "2",
                 "_score" : 1.0,
                 "_source" : {
                   "title" : "Nirvana"
                 }
               }
             ]
           }
         ]
       }
     }