如何解决Elasticsearch 6.8中模糊搜索的最佳实践是什么例如MySQL中的'%aaa%'
背景:我使用Mysql,有数百万个数据,每行有二十列,我们有一些复杂的
搜索和某些列使用模糊匹配,例如123456789.dkr.ecr.eu-west-1.amazonaws.com/my.registry.com/namespace/alpine:latest
The push refers to repository [123456789.dkr.ecr.eu-west-1.amazonaws.com/my.registry.com/namespace/alpine]
0c8667b5b: Pushed
730460948: Pushed
1.0: digest: sha256:e1f814f3818efea45267ebfb4918088a26a18c size: 7
,除非删除第一个username like '%aaa%'
,否则它不能使用mysql索引,但是我们需要模糊匹配来进行像Satckoverflow搜索这样的搜索,我还检查了Mysql { {1}},但如果使用其他索引,则不支持在一个SQL中进行复杂的搜索。
我的解决方案:将Elasticsearch添加为我们的搜索引擎,将数据插入Mysql和Es并仅在Elasticsearch中搜索数据
我检查了Elasticsearch模糊搜索,%
有用,但是很多人不建议在单词开头使用fulltext index
,这会使搜索非常慢。
例如:用户名:“ John_Snow”
wildcard
可以运行,但是速度可能很慢
*
wildcard
无效,似乎仅适用于令牌生成器,如短语“ John Snow”
GET /user/_search
{
"query": {
"wildcard": {
"username": "*hn*"
}
}
}
我的问题:有没有更好的解决方案来进行包含模糊匹配的复杂查询,例如'%no%'或'%hn_Sn%'。
解决方法
您可以使用ngram tokenizer首先将文本分解为 只要遇到指定字符列表之一, 然后它会为指定长度的每个单词发出N元语法。
添加包含索引数据,映射,搜索查询和结果的工作示例。
索引映射:
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer"
}
},"tokenizer": {
"my_tokenizer": {
"type": "ngram","min_gram": 2,"max_gram": 10,"token_chars": [
"letter","digit"
]
}
}
},"max_ngram_diff": 50
},"mappings": {
"properties": {
"title": {
"type": "text","analyzer": "my_analyzer","search_analyzer": "standard"
}
}
}
}
分析API
POST/ _analyze
{
"analyzer": "my_analyzer","text": "John_Snow"
}
令牌为:
{
"tokens": [
{
"token": "Jo","start_offset": 0,"end_offset": 2,"type": "word","position": 0
},{
"token": "Joh","end_offset": 3,"position": 1
},{
"token": "John","end_offset": 4,"position": 2
},{
"token": "oh","start_offset": 1,"position": 3
},{
"token": "ohn","position": 4
},{
"token": "hn","start_offset": 2,"position": 5
},{
"token": "Sn","start_offset": 5,"end_offset": 7,"position": 6
},{
"token": "Sno","end_offset": 8,"position": 7
},{
"token": "Snow","end_offset": 9,"position": 8
},{
"token": "no","start_offset": 6,"position": 9
},{
"token": "now","position": 10
},{
"token": "ow","start_offset": 7,"position": 11
}
]
}
索引数据:
{
"title":"John_Snow"
}
搜索查询:
{
"query": {
"match" : {
"title" : "hn"
}
}
}
搜索结果:
"hits": [
{
"_index": "test","_type": "_doc","_id": "1","_score": 0.2876821,"_source": {
"title": "John_Snow"
}
}
]
如果要进行自动完成搜索,请参考此blog。
另一个搜索查询
{
"query": {
"match" : {
"title" : "ohr"
}
}
}
上面的搜索查询没有显示结果
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。