Strict array intersection


(Ivan Orlov) #1

Hi, I have this document in elastic index:

{
    "contexts": [
        {"ref": "A"},
        {"ref": "B"} 
    ]
}

And I know some allowedRefs, different for each query.

Suppose it for example equals to

["A", "B", "C", "D", "E"].

I want to retrieve document from elastic if contexts field is empty (missing) or if allowedRefs contains ALL refs from document.

I have writen something like that:

POST /search/conversation/_search 
{
    "query": {
        "bool": {
            "should": [
                {
                    "constant_score" : {
                        "filter" : {
                            "missing" : { "field" : "contexts" }
                        }
                    }
                },
                {
                    "bool": {
                        "must": [
                            {
                                "term": { "contexts.objectRef": "A" }  // A,B,C taken from for-loop in java, for each allowedRefs
                            }, 
                            {
                                "term": { "contexts.objectRef": "B" }
                            },
                            {
                                "term": { "contexts.objectRef": "C" }
                            }
                            ...
                        ]
                    }
                }
            ]
        }
    }
}

But this is wrong because I should check presence of document's references in allowedRefs, not backward. What kind of query can help me? Should I use scripting?

In other words,

  • if document's references = A and B.
  • if allowedRefs variable (read from database in runtime) contains A, B (it can contains a lot of other values)
  • or if no references
    -> then I want to retrieve the document

(system) #2