Search code examples
elasticsearchelasticsearch-painless

How to run a query with the properties from a stored document?


Let's say we have a index with docs which contain the following fields: uid and hobbies. How can I run a query to find similarities between 1 and the other users, without having to retrieve the user first and then run a new query with his hobbies?


Solution

  • You could use the more like this query and ask ES to retrieve documents that are like a given document (e.g. user with uid=1) (without having to retrieve that document first).

    So in the like array below you simply give a reference to the document that needs to be used as a reference for the "more like this" query (you can give more than one document and also verbatim hobbies strings). ES will retrieve that document, check the hobbies field and perform a "more like this hobbies" query on all other documents.

    POST /users/user/_search
    {
        "query": {
            "more_like_this" : {
                "fields" : ["hobbies"],
                "like" : [
                  {
                    "_index" : "users",
                    "_type" : "user",
                    "_id" : "1"                <---- fill in the UID of the user here
                  }
                ]
            }
        }
    }