首页 > 解决方案 > Elasticsearch 搜索总是返回空结果

问题描述

我使用 7.6.1 版本的 Elasticsearch,我尝试索引简单对象并查询它们。我的索引没有问题,我可以按 id 查询,但是当我尝试将搜索与 Term 查询一起使用时,它会失败(0 Hit)。我不明白我做错了什么。

PUT product/_doc/b0264dad-6739-49ea-b691-e05a2883a724
{
  "name": "Name 2",
  "description": "Desc 1",
  "price": 11,
  "startSell": "2020-06-28T12:24:37.0070067+00:00",
  "endSell": "2020-07-19T12:24:37.0070161+00:00",
  "variants": [
    {
      "color": "Red",
      "size": 1
    },
    {
      "color": "Red",
      "size": 1
    },
    {
      "color": "Red",
      "size": 1
    },
    {
      "color": "Blue",
      "size": 1
    },
    {
      "color": "Yellow",
      "size": 1
    },
    {
      "color": "Yellow",
      "size": 2
    },
    {
      "color": "Yellow",
      "size": 3
    },
    {
      "color": "Purple",
      "size": 4
    }
  ]
}

有效,我可以通过它的 id 获取对象:

GET product/_doc/b0264dad-6739-49ea-b691-e05a2883a724

退货

{
  "_index" : "product",
  "_type" : "_doc",
  "_id" : "b0264dad-6739-49ea-b691-e05a2883a724",
  "_version" : 1,
  "_seq_no" : 6,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "Name 2",
    "description" : "Desc 1",
    "price" : 11,
    "startSell" : "2020-06-28T12:24:37.0070067+00:00",
    "endSell" : "2020-07-19T12:24:37.0070161+00:00",
    "variants" : [
      {
        "color" : "Red",
        "size" : 1
      },
      {
        "color" : "Red",
        "size" : 1
      },
      {
        "color" : "Red",
        "size" : 1
      },
      {
        "color" : "Blue",
        "size" : 1
      },
      {
        "color" : "Yellow",
        "size" : 1
      },
      {
        "color" : "Yellow",
        "size" : 2
      },
      {
        "color" : "Yellow",
        "size" : 3
      },
      {
        "color" : "Purple",
        "size" : 4
      }
    ]
  }
}

但是这三个请求都没有返回数据,我做错了什么?:

POST product/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "terms": {
            "name": [
              "Name 2"
            ]
          }
        }
      ]
    }
  }
}


POST product/_search
{
  "query": {
    "term": {
      "name": {
        "value": "Name 2",
        "boost": 1
      }
    }
  }
}

POST product/_search
{
  "query": {
    "term": {
      "description": {
        "value": "Desc 1",
        "boost": 1
      }
    }
  }
}

标签: elasticsearchsearch

解决方案


主要是因为这些字段namedescription被定义为text索引中的字段,standard analyzer默认情况下使用 并在空格上拆分,因此为这些字段生成的标记将为您 的字段和name字段。2namedesc1description

当您使用term未分析的查询并尝试匹配name 2不存在的令牌时。

解决方法:将查询改为match查询,否则.keyword如果自动生成映射则使用该字段,或者如果您打算使用该term查询,则定义一个关键字字段来存储数据。

通过示例参考差异 b/w 术语与匹配查询


推荐阅读