愚者求师之过,智者从师之长。

请教大神,关于部分匹配的问题

Elasticsearch | 作者 caochuansong | 发布于2017年06月07日 | 阅读数:3082

小白提问:
我有一个客户列表可能几百万条,例如:
上海测试1有限公司
上海测试2有限公司
如何让用用户输入“试1”的时候能搜索出结果,如果用wildcard:*试1* 是不是效率很低,效率高的方式是什么?
已邀请:

kennywu76 - Wood

赞同来自: caochuansong

自定义一个analyzer,将tokenizer配置为ngram,https://www.elastic.co/guide/e ... .html
 
例如:
PUT my_index
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer"
}
},
"tokenizer": {
"my_tokenizer": {
"type": "ngram",
"min_gram": 2,
"max_gram": 2,
"token_chars": [
"letter",
"digit"
]
}
}
}
},
"mappings": {
"company": {
"properties": {
"name": {
"type": "text",
"analyzer": "my_analyzer"
}
}
}
}
}

 写入测试数据:
上海测试有限公司
上海测试1有限公司
上海测试2有限公司

 
用match query搜索"试1",只会match一条
POST my_index/_search
{
"query": {
"match": {
"name": "试1"
}
}
}

{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.62191015,
"hits": [
{
"_index": "my_index",
"_type": "company",
"_id": "AVyCIZF6MEN3nKM0AYMh",
"_score": 0.62191015,
"_source": {
"name": "上海测试1有限公司"
}
}
]
}
}

如果搜索“测试1”,则会match所有3条,不过匹配度高的评分较高,排序在前。
POST my_index/_search
{
"query": {
"match": {
"name": "测试1"
}
}
}

{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 0.78549397,
"hits": [
{
"_index": "my_index",
"_type": "company",
"_id": "AVyCIZF6MEN3nKM0AYMh",
"_score": 0.78549397,
"_source": {
"name": "上海测试1有限公司"
}
},
{
"_index": "my_index",
"_type": "company",
"_id": "AVyCIarGMEN3nKM0AYMj",
"_score": 0.28582606,
"_source": {
"name": "上海测试有限公司"
}
},
{
"_index": "my_index",
"_type": "company",
"_id": "AVyCIZzCMEN3nKM0AYMi",
"_score": 0.16358379,
"_source": {
"name": "上海测试2有限公司"
}
}
]
}
}

 
 

caochuansong

赞同来自:

谢谢大神给的思路,我在研究一下

要回复问题请先登录注册