ElasticSearch 設置某個欄位不分詞

先說結論:欄位類型更改為 ‘keyword’

elasticSearch官方文檔中創建index程式碼如下

複製程式碼
PUT /my_store 
{
    "mappings" : {
        "products" : {
            "properties" : {
                "productID" : {
                    "type" : "string",
                    "index" : "not_analyzed" 
                }
            }
        }
    }

}
複製程式碼

由於es官方文檔版本基於2.x編寫,而本人安裝版本為6.6 在執行如上程式碼過程中出現如下錯誤

No handler for type [string] declared on field [productID]

 

 

 這裡報錯是因為ElasticSearch5.x以上版本沒有string類型了,換成了text和keyword作為字元串類型。


 

字元串 – text:用於全文索引,該類型的欄位將通過分詞器進行分詞,最終用於構建索引

字元串 – keyword:不分詞,只能搜索該欄位的完整的值,只用於 filtering

此時我們將文檔中程式碼更改為如下

複製程式碼
PUT /my_store 
{
    "mappings" : {
        "products" : {
            "properties" : {
                "productID" : {
                    "type" : "keyword",
                    "index": true
                }
            }
        }
    }
}
複製程式碼

 

 

 創建成功,此時我們進行查詢試試看

複製程式碼
GET /my_store/products/_search
{
    "query" : {
        "constant_score" : {
            "filter" : {
                "term" : {
                    "productID" : "XHDK-A-1293-#fJ3"
                }
            }
        }
    }
}
複製程式碼