不为失败找理由,要为成功找方法。

如何查找出两两相似的数据?

Elasticsearch | 作者 WilsonZhu233 | 发布于2021年03月08日 | 阅读数:921

最近遇到一个需求, 用户想要查出相似的数据;
比如有两家单位, 一个叫 "某某有限公司" ,一个叫 "某某有限公司1";
现在想把这些两两相似的数据都查出来, 我试了遍历全表,每条数据写一个query去查, 发现实在是太慢了;
不知道有没有更好的方式去实现这种查询?
 
目前已实现根据输入的字符串去查询(自己用java写了个基于编辑距离的相似度评分插件):
PUT /units
{
"settings": {
"number_of_replicas": 0,
"number_of_shards": 1,
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer"
}
},
"tokenizer": {
"my_tokenizer": {
"type": "simple_pattern",
"pattern": "[A-Za-z0-9\u4e00-\u9fa5]"
}
}
}
},
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"unifiedCode": {
"type": "text",
"analyzer": "my_analyzer",
"similarity": "boolean"
},
"unitName": {
"type": "text",
"analyzer": "my_analyzer",
"similarity": "boolean"
},
"unitType": {
"type": "keyword"
},
"contactsTel": {
"type": "keyword"
},
"artificial": {
"type": "keyword"
},
"createTime": {
"type": "keyword"
}
}
}
}
POST /units/_bulk
{ "create" : {"_id" : "1621211319" } }
{"id":"039c4e6d-41fc-4fee-9f9e-025d5084ae77", "unifiedCode":"测试", "unitName":"某某有限公司", "unitType":"测试", "contactsTel":"", "artificial":"", "createTime":"2021-01-27 15:37:27.0"}
{ "create" : {"_id" : "509930157" } }
{"id":"04d8d602-37dd-42ee-95de-634875e1b979", "unifiedCode":"测试1", "unitName":"某某有限公司1", "unitType":"测试", "contactsTel":"", "artificial":"", "createTime":"2009-11-24 08:00:00.0"}
{ "create" : {"_id" : "1729683709" } }
GET /units/_search
{
"query": {
"script_score": {
"query": {
"match": {
"unitName": {
"query": "某某有限公司",
"minimum_should_match": "90%" // 这里先按照频数进行查询
}
}
},
"script": {
"source": "string_similarity", // 调用评分插件, 返回基于编辑距离的相似度
"lang": "expert_scripts",
"params": {
"field": "unitName", // 字段
"term": "某某有限公司" // 值
}
},
"min_score": 0.9 // 限制相似度, 大于等于90%
}
},
"from": 0,
"size": 10
}


现在为了找出表中相似的数据, 先把整张表的数据查出, 然后循环构造类似上方的query语句, 命中两条及以上数据就说明表中有相似数据, 加到返回结果;
几千条数据, 竟然要耗费几分钟 .
不知道有没有更完美的方式去实现这种查询?
 
已邀请:

CurryQin

赞同来自: WilsonZhu233

试试span_near

laoyang360 - 《一本书讲透Elasticsearch》作者,Elastic认证工程师 [死磕Elasitcsearch]知识星球地址:http://t.cn/RmwM3N9;微信公众号:铭毅天下; 博客:https://elastic.blog.csdn.net

赞同来自: WilsonZhu233

这个问题非常有意思。我认为应该在写入的时候做处理,而不应该是做检索的时候做处理。
我这边做过大数据舆情的场景,对象是文本的处理,我们采取的策略就是写入的时候通过simhash计算文本之间的相似值。
然后检索的时候就会非常方便。

PythonLee - 90后IT男

赞同来自:

Suggest

要回复问题请先登录注册