人名的 ElasticSearch 查询问题

Anj*_*y V 3 elasticsearch

我们有一个文本字段,其中包含带有首字母的人名,这些首字母不一致(有些地方用空格/点分隔,有些地方不)。

例如:- GJ Raja,G。J.拉贾,GJ 拉贾,GJ 拉贾...

我尝试了以下解决方案,但无法获得预期的解决方案

  1. 使用标准分析器 - 我能够管理空间和点但不能做第三个例子(GJ Raja)
  2. 使用边缘 ngram - 如果我使用 search_as_you_type 它会花费很多时间(它有超过 100 000 条记录)
  3. 使用同义词 - AWS 不支持同义词路径,每次都将这些记录放入内联映射和索引中。

输入:- GJ Raja

输出:- GJ Raja,G。J.拉贾,GJ 拉贾,GJ 拉贾

Val*_*Val 5

使用pattern_replace令牌过滤器,您可以实现您想要的。以下调用的分析器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"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以索引一些文档

PUT test/_bulk
{"index": {}}
{"name": "G.J. Raja"}
{"index":{}}
{"name":"G . J . Raja"}
{"index": {}}
{"name":"GJ Raja"}
{"index":{}}
{"name":"G J Raja"}
Run Code Online (Sandbox Code Playgroud)

最后,以下查询将找到所有四个不同的名称(以及其他变体)。您也可以搜索G. J. RajaorG. J Raja并且所有四个文档都将匹配:

POST test/_search 
{
  "query": {
    "match": {
      "name": "G J Raja"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

结果:

{
  "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"
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)