我们有一个文本字段,其中包含带有首字母的人名,这些首字母不一致(有些地方用空格/点分隔,有些地方不是)。
例如:- G.J.拉贾,G。 J. Raja,GJ Raja,G J Raja ...
我尝试了以下解决方案,但无法获得预期的解决方案
- 使用标准分析器 - 我能够管理空间和点但不能 做第三个例子(GJ Raja)
- 使用边缘 ngram - 如果我使用 search_as_you_type 它会花费很多时间 (它有超过 100 000 条记录)
- 使用同义词 - AWS 不支持同义词路径并将这些 每次在内联映射和索引中都有很多记录。
输入:- G J Raja
输出:- G.J.拉贾,G。 J. Raja,GJ Raja,G J Raja
最佳答案
使用 pattern_replace
token filter ,你可以实现你想要的。以下名为 initial_analyzer
的分析器将清理您的姓名并确保所有姓名都转换为 GJ Raja
PUT test
{
"settings": {
"index": {
"analysis": {
"analyzer": {
"initial_analyzer": {
"type": "custom",
"tokenizer": "keyword",
"filter": [
"initials"
]
}
},
"filter": {
"initials": {
"type": "pattern_replace",
"pattern": """[\.\s]*([A-Z])[\.\s]*([A-Z])[\.\s]*(\w+)""",
"replacement": "$1$2 $3"
}
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "text",
"analyzer": "initial_analyzer"
}
}
}
}
然后我们可以索引一些文档
PUT test/_bulk
{"index": {}}
{"name": "G.J. Raja"}
{"index":{}}
{"name":"G . J . Raja"}
{"index": {}}
{"name":"GJ Raja"}
{"index":{}}
{"name":"G J Raja"}
最后,以下查询将找到所有四个不同的名称(以及其他变体)。您还可以搜索 G。 J. Raja
或 G. J Raja
和所有四个文档将被匹配:
POST test/_search
{
"query": {
"match": {
"name": "G J Raja"
}
}
}
结果:
{
"took" : 4,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 4,
"max_score" : 0.18232156,
"hits" : [
{
"_index" : "test",
"_type" : "doc",
"_id" : "Z7pF7WwBvUQmOB95si05",
"_score" : 0.18232156,
"_source" : {
"name" : "G . J . Raja"
}
},
{
"_index" : "test",
"_type" : "doc",
"_id" : "aLpF7WwBvUQmOB95si05",
"_score" : 0.18232156,
"_source" : {
"name" : "GJ Raja"
}
},
{
"_index" : "test",
"_type" : "doc",
"_id" : "ZrpF7WwBvUQmOB95si05",
"_score" : 0.18232156,
"_source" : {
"name" : "G.J. Raja"
}
},
{
"_index" : "test",
"_type" : "doc",
"_id" : "abpF7WwBvUQmOB95si05",
"_score" : 0.18232156,
"_source" : {
"name" : "G J Raja"
}
}
]
}
}
关于ElasticSearch 查询问题与人的初始名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57712245/