Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter by field values in ElasticSearch?

Tags:

Given the ElasticSearch document below:

{
    "_id": "3330481",
    "_type": "user",
    "_source": {
        "id": "3330481",
        "following": ["1", "2", "3", ... , "15000"]
    }
}

For a given user list ["50", "51", "52"] I want to check which ones are followed by the user with id 3330481. Since she is following 15000 users, I don't want to get the whole list and then check it locally.

Is there any way to retrieve only the relevant users?

like image 431
fkoksal Avatar asked Mar 23 '16 20:03

fkoksal


1 Answers

I am not sure whether you can fetch a sub-array from a doc.

However, one way of achieving this is by using nested fields. You can change the schema of following field to be nested as below.

 {
        "id": "3330481",
        "following": [
              {"userId":"1"}, {"userId":"2"},{"userId": "3"}, ... ]
 }

Then you can use inner_hits to retrieve your matching elements in the array as below.

{
    "query" : {
        "nested" : {
            "path" : "following",
            "query" : {
                "terms" : {"following.userId" : ["50","51","53"]}
            },
            "inner_hits" : {
                "size":0 // fetches all 
            }
        }
    }
}
like image 124
Rahul Avatar answered Oct 03 '22 18:10

Rahul