13

I am trying to write a query using query_string to retrieve data querying by nested objects.

An example of query I would like to do is this one:

{
  "query": {
    "query_string": {
      "query": "a.id:2"
    }
  }
}

Where "a" is a nested object, and "id" is a field of "a".

I know I can successfully perform this task using using a nested query, writing a query like:

{
  "nested": {
    "path": "a"
    "query_string": {
      "query": "a.id:2"
    }
  }
}

However, I would like to avoid it. I don't want to figure out by myself that the user is searching for a nested field and modify the query. I tried to use the "fields" parameter, but it looks like it doesn't work with nested objects.

Is it possible to write this query directly using "query_string" queries? What semantic is it possible to obtain? (for instance, if I write "a.id:2 AND a.b:10" I am matching the two fields in the same object or in different objects?)

Cale
  • 361
  • 3
  • 10
  • I'm trying to find an answer to this very same question. Just wondering if you were able to find any solution yet. Any help would be great! Thanks – Vineet May 10 '15 at 01:25
  • Unfortunately I didn't find a solution. – Cale May 10 '15 at 15:03

1 Answers1

15

I was doing more research and found this can be achieved by setting the include_in_parent setting to true in the mapping.

Now you should be able to do a query like

{
  "query": {
    "query_string": {
      "query": "fields.fieldvalue:sometext"
    }
  }
}

Eg:-

"mappings": {
         "documentmetadatavalue": {
            "properties": {
              "id": {
                  "type": "string"
               },
               "fields": {
                 "type": "nested",
                 "include_in_parent": true, 
                 "properties": {
                   "fieldId": {"type": "string"},
                   "fieldvalue": {"type": "string"}
                 }
               }
           }
        }
     }

Let me know if that helps.

Vineet
  • 401
  • 5
  • 15
  • 8
    What you propose is a good alternative. Note, however, that with the setting "include_in_parent" you are flattening the nested resource as an object in the parent. You are actually reindexing the document as a flattened object. You are losing some nice feature of nested objects. For instance, if you search for parent objects having at least ONE child with TWO attributes with a specific value, the query will not check that the TWO attributes have those values in a unique child. – Cale May 11 '15 at 13:21
  • Check out the documentation of inner_hits which was recently released. You should be able to make it work with this new feature. (https://www.elastic.co/guide/en/elasticsearch/reference/1.x/search-request-inner-hits.html#nested-inner-hits – Vineet May 16 '15 at 21:38