ElasticSearch: search inside the array of objects

后端 未结 2 1557
青春惊慌失措
青春惊慌失措 2021-02-01 08:41

I have a problem with querying objects in array. Let\'s create very simple index, add a type with one field and add one document with array of objects (I use sense console):

相关标签:
2条回答
  • 2021-02-01 09:25

    Here's one way you can do it, using nested docs:

    I defined an index like this:

    PUT /test_index
    {
       "mappings": {
          "doc": {
             "properties": {
                "parent": {
                   "type": "nested",
                   "properties": {
                      "label": {
                         "type": "string"
                      },
                      "name": {
                         "type": "string"
                      }
                   }
                }
             }
          }
       }
    }
    

    Indexed your document:

    PUT /test_index/doc/1
    {
       "parent": [
          {
             "name": "turkey",
             "label": "Turkey"
          },
          {
             "name": "turkey,mugla-province",
             "label": "Mugla (province)"
          }
       ]
    }
    

    Then either of these queries will return it:

    POST /test_index/_search
    {
        "query": {
            "nested": {
               "path": "parent",
               "query": {
                   "match": {
                      "parent.name": "turkey"
                   }
               }
            }
        }
    }
    
    POST /test_index/_search
    {
        "query": {
            "nested": {
               "path": "parent",
               "query": {
                   "match": {
                      "parent.name": "turkey,mugla-province"
                   }
               }
            }
        }
    }
    

    Here's the code I used:

    http://sense.qbox.io/gist/6258f8c9ee64878a1835b3e9ea2b54e5cf6b1d9e

    0 讨论(0)
  • 2021-02-01 09:29

    For search multiple terms use the Terms query instead of Term query.

    "terms" : {
            "tags" : [ "turkey", "mugla-province" ],
            "minimum_should_match" : 1
        }
    

    There are various ways to construct this query, but this is the simplest and most elegant in the current version of ElasticSearch (1.6)

    0 讨论(0)
提交回复
热议问题