ES 筆記二十七:自動補全與機遇上下文的提示

CrazyZard發表於2019-11-27
  • Completion Suggester 提供了“自動完成”(Auto Complete)的功能。使用者每輸入一個字元,就需要即時傳送一個插敘請求到後端查詢匹配項
    • 對效能要求比較苛刻。ES採用了不同的資料結構,並非通過倒排索引來完成。而是將Analyze 的資料編碼成FST和索引一起存放。FST會被ES整個載入進內容,速度很快
    • FST只能用於字首查詢

使用Completion Suggester 一些步驟

  • 定義Mapping,使用“completion” type
  • 索引資料
  • 執行“suggest”查詢,得到搜尋建議
//定義mapping
PUT articles
{
  "mappings": {
    "properties": {
      "title_completion": {
        "type": "completion"
      }
    }
  }
}
//寫入資料
POST articles/_bulk
{"index":{}}
{"title_completion":"lucene is very cool"}
{"index":{}}
{"title_completion":"Elasticsearch builds on top of lucene"}
{"index":{}}
{"title_completion":"Elasticsearch rocks"}
{"index":{}}
{"title_completion":"elastic is the company behind ELK stack"}
{"index":{}}
{"title_completion":"Elk stack rocks"}
{"index":{}}
//查詢
POST articles/_search?pretty
{
  "size": 0,
  "suggest": {
    "article-suggest": {
      "prefix": "e", //查詢欄位 
      "completion": {
        "field": "title_completion"
      }
    }
  }
}
  • Completion Suggester 的擴充套件
  • 可以在搜尋中加入耕讀偶讀上下文資訊,例如,輸入“star”
    • 咖啡相關:starbucks
    • 電影相關:star wars
  • 可以定義兩種型別的Context
    • Category - 任意的字串
    • Geo - 地理資訊位置
  • 實現Context Suggester
    • 定製一個Mapping
    • 索引資料,並且為每個文件加入Conetxt資訊
    • 結合Context 進行Suggestion 查詢
PUT comments
PUT comments/_mapping
{
  "properties":{
    "comment_autocomplete":{
      "type":"completion",
      "contexts":[{
       "type":"category",
       "name":"comment_category"
      }]
    }
  }
}
POST comments/_doc
{
  "comment": "I love the star war movies",
  "comment_autocomplete": {
    "input": ["star wars"],
    "contexts": {
      "comment_category": "movies"
    }
  }
}
POST comments/_doc
{
  "comment":"Where can I find a Starbucks",
  "comment_autocomplete":{
    "input":["starbucks"],
    "contexts":{
      "comment_category":"coffee"
    }
  }
}
POST comments/_search
{
  "suggest": {
    "MY_SUGGESTION": {
      "prefix": "sta",
      "completion":{
        "field":"comment_autocomplete",
        "contexts":{
         "comment_category":"movies" 
        //  "comment_category":"coffee"  
        }
      }
    }
  }
}
  • 精準度
    • Completion > Phrase > Term
  • 召回率
    • Term > Phrase > Completion
  • 效能
    • Completion > Phrase > Term

快樂就是解決一個又一個的問題!

相關文章