bakayim
bakayim

Reputation: 210

Elasticsearch nested type select query

I have a field with mapping:

   "my_field_name": {
            "type": "nested",
            "properties": {
              "labels": {
                "type": "text"
              },
              "source": {
                "type": "text"
              }
            }
          }

and when I put data, format is like:

"my_field_name": {
            "url_of_an_image": [
              "tag1",
              "tag2",
              "tag3",
              "tag4",
              "tag5"
            ],
            "url_of_an_image2": [
              "tag4",
              "tag5",
              "tag6",
              "tag7",
              "tag8"
            ]
}

I want to write an elasticsearch query to gather all the documents that contains given tag.

How can I search a tag in all documents and select the ones that contains given tag?

Thank you

Upvotes: 0

Views: 284

Answers (2)

glenacota
glenacota

Reputation: 2547

(EDITED AFTER COMMENT)

As a first consideration, the mapping doesn't match the structure of your document, e.g., my_field_name has neither labels nor source fields. Which is the one that better represents your data?

As a second consideration, in your comment you said that

while querying I don't know "url_of_an_image" since it is different for each document

However, from your example, it looks like url_of_an_image is a property of the items of my_field_name rather than of the document. Therefore, I'd suggest doing something like:

"my_field_name": [
  {
    "image_url": "url_of_an_image",
    "tags": [
       "tag1",
       "tag2",
       "tag3",
       "tag4",
       "tag5"
    ]
  },
  {
    "image_url": "url_of_an_image2",
    "tags": [
       "tag4",
       "tag5",
       "tag6",
       "tag7",
       "tag8"
    ]
  }
]

And this would be the mapping:

"my_field_name": {
  "type": "nested",
  "properties": {
     "image_url": {
       "type": "text"
     },
     "tags": {
       "type": "text"
    }
  }
}

This way, you can run queries like:

{
  "query": {
    "nested" : {
      "path" : "my_field_name",
      "query" : {
        "bool" : {
          "must" : [
            { "match" : {"my_field_name.image_url" : "url_of_an_image2"} },
            { "match" : {"my_field_name.tags" : "tag3"} }
          ]
        }
      }
    }
  }
}

Upvotes: 1

core
core

Reputation: 871

You can achieve this by using the Nested Query: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html

Upvotes: 0

Related Questions