首页 > 解决方案 > How to search data that not in the object in Elasticsearch using Nested?

问题描述

I try to search categories and products in Elasticsearch using Nested type.

I have data like this:

POST products/_doc
{
  "id" : 1,
  "category_id" : 1,
  "category_name" : "Test Category",
  "name": "Sapiente",
  "attributes" : [
    {
      "color" : "blue",
      "size" : 8
    },
    {
      "color" : "black",
      "size" : 16
    }
  ]
}

and I try to search on this data like this :

GET products/_search
{
  "query": {
    "nested": {
      "path": "attributes",
      "query": {
        "bool": {
          "filter": [
            {
              "term": {
                "name.keyword": "Sapiente"
              }
            }
          ]
        }
      }
    }
  }
}

But i didn't understand to how i can search for NAME or CATEGORY_NAME fields. I can only search data that in the attributes object otherwise i get empty result.

Is that possible to search both NAME, CATEGORY_NAME and data in ATTRIBUTES object ?

Thank you in advance...

标签: objectelasticsearchsearchnested

解决方案


您可以使用布尔查询来组合嵌套和非嵌套查询

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "attributes",
            "query": {
              "bool": {
                "filter": [
                  {
                    "term": {
                      "attributes.color": "blue"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "term": {
            "name.keyword": "Sapiente"
          }
        }
      ]
    }
  }
}

推荐阅读