Query to get all the children

Here is mapping

PUT my_index
{
  "mappings": {
    "properties": {
      "my_join_field": {
        "type": "join",
        "relations": {
          "parent": "child"
        }
      },
      "name": { "type": "keyword" },
      "age": { "type": "integer" },
      "hobby": { "type": "keyword" }
    }
  }
}

I want to get all the children.

GET my_index/_search
{
  "query": {
    "has_parent": {
      "parent_type": "parent",
      "query": {
        "match_all": {}
      }
    }
  }
}

It returns all the children in below response format

{
        "_index": "my_index",
        "_id": "child1",
        "_score": 1,
        "_routing": "parent1",
        "_source": {
          "name": "Alice Doe",
          "age": 10,
          "hobby": "reading",
          "my_join_field": {
            "name": "child",
            "parent": "parent1"
          }
        }
      }

I run a different query

GET my_index/_search
{
  "query": {
    "term": {
      "my_join_field": "child"
    }
  }
}

It returns all the children in below response format. Notice the score is different than previous result

{
        "_index": "my_index",
        "_id": "child1",
        "_score": 0.44183272,
        "_routing": "parent1",
        "_source": {
          "name": "Alice Doe",
          "age": 10,
          "hobby": "reading",
          "my_join_field": {
            "name": "child",
            "parent": "parent1"
          }
        }
      }

Is the 2nd query still correct? Why score is different.

Hi @yulinxp :

Scoring will be different in the two queries as they are different queries.

  • The first is a match_all query, which has a constant score of 1.
  • The second is a term query, which actually calculates a score based on the term frequency and document frequency.

Your queries seem correct, but as they are different, different score is returned by them.

If you just want to retrieve your parents / children and not to actually perform scoring depending on a text query, you should use a filter or wrap your term query in a constant score query so it's more efficient (as it won't calculate scores that way).

Hope that helps!

Thank you!