eddyP23
eddyP23

Reputation: 6845

Elastic Search - querying documents where intersection of two arrays is nonempty

I have a document structure as follows:

{ 
    "documentId": 123,
    "someOtherInfo": {...}
    "permissions": ["a", "b, ..., "g"]
}

Users themselves have a permission set ["x", "y", "z"]. Business Rule: User A is allowed to view document X if and only if at least one of the user permissions matches documents permissions. Or put mathematically, if intersection is nonempty -

["a", "b, ..., "g"] ∩ ["x", "y", "z"] ≠ ∅

I am building a search engine that needs to find all documents user has access to. I want to store it in Elastic Search for all the great querying capabilities it provides, but how do I add a restriction for permissions using ES DSL? Many thanks.

Upvotes: 1

Views: 480

Answers (1)

Jai Sharma
Jai Sharma

Reputation: 733

You need a terms query where an array whose element is to be matched can be passed. This match documents containing any of the provided terms. As an example , the following will match the document containing permissions = ["a", "b", "c"] but not permissions = ["a", "t", "c"]

{
  "query": {
    "terms": {
      "permissions": [
        "x",
        "y",
        "z",
        "b"
      ]
    }
  }
}

Upvotes: 2

Related Questions