Elastic search Add additional condition if type is different

I have 2 sets of documents, which are joined by fragmentId . I have written a query that pulls both documents, but I am thinking is there any other way to write it.

Parent Document - There could be only 1 such document which has type = fragment and fragmentId = 1

Multiple Child Documents - All will have type=cf, and fragmentId = 1, they will have start and end values. which will distinguish the children.

GET test/_search
{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "fragmentId": "1"
                }
              },
              {
                "term": {
                  "type": "fragment"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "fragmentId": "1"
                }
              },
              {
                "term": {
                  "type": "cf"
                }
              },
              {
                "range" :{
                  "start": {
                    "gte": 1,
                    "lte": 5
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

In the above query, you can see, I need to duplicate the condition for type and fragment id, as when type=cf, I have to add an extra range filter.

Is there a way to re-write this query in a more simple form, basically a join operation on fragmentId
like a parent-child relationship, with an extra check on child docs.?

like this ? or you want script search?

GET test/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "fragmentId": "1"
          }
        }
      ],
      "should": [
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "type": "cf"
                }
              },
              {
                "range": {
                  "start": {
                    "gte": 1,
                    "lte": 5
                  }
                }
              }
            ]
          }
        },
        {
          "term": {
            "type": "fragment"
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}
1 Like

Thanks for the reply, yes this helps in re-structuring the query correctly.
But is it possible to write a query in such a way that if type =" fragment" and fragment id = 1, is not present, then it should not pick the other document with type="cf".
Basically, I want the combo of both documents, or else no result.

maybe you can try script, However, it’s not recommended and unnecessary

1 Like

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