Or query in ES

Hello,

Given a couple<key,value> I want to create a query to find documents where a nested field contains the couple <key,value> .

The structure is like this:

"f1":{
"key":"K1",
"value","V1"},
"f2":{
"key":"K2",
"value","V2"},
"f3":{
"key":"K3",
"value","V3"}

I've created this query for this couple <Key1,Value1>:

GET myIndex/environment/_search
{
"query": {
"nested": {
"path" : "f1",
"query": {
"bool": {
"must": [{
"match": {
"f1.key": "Key1"
}
},
{"match": {
"f1.value": "Value1"
}
}]
}
}
}
}
}

It searches only in f1, I want to khnow if f1 or f2 or f3 contains that couple in one query.

Thanks fo help.

I think you want should inside of bool. Also, I think you want nested queries inside the should, but I'm not exactly sure what kind of search you are going for.

I want to return document if one of f1 or f2 or f3 fileds matchs the couple <Key1,Value1> . I'm newbie in ES and can't create such query.

To be honest nested makes you life harder as a newbie even if it is what you want in the end. Are you sure you need it yet? Without nested I'd reach for multimatch. With nested you'll write much more json.

The problem without nested I can't match f1.key and f1.vlaue.. I should add the path so I need to use nested.

Right. In that case it looks more like:

GET /_search
{
  "query": {
    "bool": {
      "should": [
        "nested" : {
            "path" : "f1",
            "query" : {
                "bool" : {
                    "must" : [
                      { "match" : {"f1.key" : "blue"} },
                      { "match" : {"f1.value" : "bar"} }
                    ]
                }
            }
        },
        "nested" : {
            "path" : "f2",
            "query" : {
                "bool" : {
                    "must" : [
                      { "match" : {"f2.key" : "blue"} },
                      { "match" : {"f2.value" : "bar"} }
                    ]
                }
            }
        },
        "nested" : {
            "path" : "f3",
            "query" : {
                "bool" : {
                    "must" : [
                      { "match" : {"f3.key" : "blue"} },
                      { "match" : {"f3.value" : "bar"} }
                    ]
                }
            }
        }
    }
}

But remember the whole point of nested is so that f1 can have multiple values and you can correlate them. Unless you really need f1, f2, and f3 to be separate fields for some other reason, it is worth looking at combining them.

1 Like

It works, Thank you very much !

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