// 本来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": {}
}