Identify if hit is on main document or on its nested field documents

I have a document that have a nested field. My query searches on both main document fields and its nested fields (using OR logic between main and nested field sets) but then I need to know if the hit was on main document or on one of its nested documents or on both. Using inner hits I can always tell which (if any) nested documents was a hit but I can't say if the main document itself was a hit or not.
I could do it by executing the query twice first on main document and nested fields and based the result set execute the same query against primary document fields only with addition of terms query on document ID with IDs from the first query. the second query result could be used to identify main document matches.

If possible I would like to avoid the multi-step process mentioned above as it does not play very well with UI framework I am using so any suggestion is greatly appreciated

My business case is:

I have primary records and secondary records that have the same structure. I store primary and secondary records in the same index distinguished by a flag. Primary records also have array of their secondary records as a nested field. one of the use cases I have is to find all primary records where criteria matches the primary or any of its secondary records in order of combined (primary plus all secondaries) relevance presenting primary record and all its secondaries to the users identifying (highlighting) specific secondaries and primaries that caused the match.

You can name the parent query and if it was hit you will see its name in the matched_queries list. Basically this:

DELETE my_index

PUT my_index
{
    "mappings": {
        "_doc" : {
            "properties" : {
                "obj1" : {
                    "type" : "nested"
                }
            }
        }
    }
}

PUT my_index/_doc/1
{
  "foo": "bar",
  "obj1": {
    "foo": "baz"
  }
}

POST my_index/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "obj1",
            "score_mode": "avg",
            "query": {
              "match": {
                "obj1.foo": {
                  "query": "baz"
                }
              }
            },
            "_name": "child"
          }
        },
        {
          "match": {
            "foo": {
              "query": "bar",
              "_name": "parent"
            }
          }
        }
      ]
    }
  }
}

Oh great thank you Igor!
I thought I saw some mechanism in elastic for distinguishing query branches but could not remember what it was

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.