Elasticsearch實現變態的精確匹配,配置分析器
// 本來es搜尋引擎可以支援的是語義的模糊搜尋,但是有些需求要求精確搜尋匹配,用自定義的配置分析器可以實現精確搜尋
https://www.elastic.co/guide/en/elasticsearch/reference/5.6/analysis-ngram-tokenizer.html#analysis-ngram-tokenizer
// 官網例子
// 配置自定義分析器
curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer"
}
},
"tokenizer": {
"my_tokenizer": {
"type": "ngram",
"min_gram": 3,
"max_gram": 3,
"token_chars": [
"letter",
"digit"
]
}
}
}
}
}
'
或者
// 不區分大小寫
curl -XPUT 'localhost:9200/my_index/_settings?pretty' -H 'Content-Type: application/json' -d'
{
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer",
"filter": [
"lowercase"
]
}
},
"tokenizer": {
"my_tokenizer": {
"type": "ngram",
"min_gram": 1,
"max_gram": 50,
"token_chars": []
}
}
}
}
'
// 進行測試
curl -XPOST 'localhost:9200/my_index/_analyze?pretty' -H 'Content-Type: application/json' -d'
{
"analyzer": "my_analyzer",
"text": "2 Quick Foxes."
}
'
// 在Mapping上,為欄位field配置應用的分析器
// field
curl -XPUT 'localhost:9200/my_index/_mapping/typeabc' -H 'Content-Type: application/json' -d'
{
"typeabc": {
"properties": {
"field": {
"type": "text",
"analyzer": "my_tokenizer"
}
}
}
}
'
// 搜尋例子
// field1欄位可能是個陣列,並且field1的欄位值也可能會提供另一個值來做查詢
{
"method": "POST",
"path": "/my_index/typeabc/_search",
"body": {
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
"match": {
"field1": {
"query": "xxx/xxx/xx1",
"minimum_should_match": "100%"
}
}
},
{
"match": {
"field1": {
"query": "xxx/xxx/xx2",
"minimum_should_match": "100%"
}
}
}
],
"minimum_should_match": 1
}
},
{
"match": {
"field1": {
"query": "xxx/xxx/xx",
"minimum_should_match": "100%"
}
}
},
{
"range": {
"field4Time": {
"lte": "new Date()"
}
}
}
],
"should": [
{
"match": {
"field6": {
"query": "xxx",
"minimum_should_match": "100%"
}
}
},
{
"match": {
"field7": {
"query": "xxx",
"minimum_should_match": "100%"
}
}
}
],
"minimum_should_match": 1
}
},
"sort": {
"field4Time": {
"order": "desc"
}
},
"from": 0,
"size": 10
},
"query": {}
}
// 總結起來如下
{
"method": "POST",
"path": "/index/type/_search",
"body": {
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
"match": {
}
},
{
"match": {
}
}
],
"minimum_should_match": 1
}
},
{
"match": {
}
},
{
"match": {
}
},
{
"range": {
}
}
],
"should": [
{
"match": {
}
},
{
"match": {
}
}
],
"minimum_should_match": 1
}
},
"sort": {
},
"from": 0,
"size": 10
},
"query": {}
}