Elasticsearch将名称与首字母匹配

时间:2019-05-01 12:56:07

标签: elasticsearch

我正在使用Elasticsearch搜索模板的胡子语言

搜索“ Joe Gray”将返回名为“ Joe Gray”的任何人,或者搜索“ J Gray”将返回“ Joe Gray”。

但是搜索“ Joe Gray”不会返回任何带有“ J Gray”的名称

如何在胡子查询中使用分析器来实现这一目标。

1 个答案:

答案 0 :(得分:0)

不太清楚您的索引映射是什么样的。我在这里有两个例子:

1 名称包含在一个字段中:

    PUT t2/doc/1
    {
      "name":"Joe Gray"
    }

    PUT t2/doc/2
    {
      "name":"J Gray"
    }

    POST t2/_search
    {
      "query": {
        "match": {
          "name": "j gray"
        }
      }
    }

##Result

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0.51623213,
    "hits": [
      {
        "_index": "t2",
        "_type": "doc",
        "_id": "2",
        "_score": 0.51623213,
        "_source": {
          "name": "J Gray"
        }
      },
      {
        "_index": "t2",
        "_type": "doc",
        "_id": "1",
        "_score": 0.25811607,
        "_source": {
          "name": "Joe Gray"
        }
      }
    ]
  }
}

2如果您将名称作为两个单独的字段(根据我在评论中注意到的内容)-您可以对bool子句使用should查询:

PUT t3/doc/1
{
  "firstname":"Joe",
  "lastname":"Gray"
}

PUT t3/doc/2
{
  "firstname":"J",
  "lastname":"Gray"
}


POST t3/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "firstname": "J"
          }
        },
        {
          "match": {
            "lastname": "Gray"
          }
        }
      ]
    }
  }
}

## Result

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0.5753642,
    "hits": [
      {
        "_index": "t3",
        "_type": "doc",
        "_id": "2",
        "_score": 0.5753642,
        "_source": {
          "firstname": "J",
          "lastname": "Gray"
        }
      },
      {
        "_index": "t3",
        "_type": "doc",
        "_id": "1",
        "_score": 0.2876821,
        "_source": {
          "firstname": "Joe",
          "lastname": "Gray"
        }
      }
    ]
  }
}