Global Warrior
Global Warrior

Reputation: 5110

Elasticsearch find documents by another document

I want to search documents in elasticsearch which have exactly same fields as the given document of id docId. For e.g. user calls the api with a docId, I want to filter docs such that all the docs returned fulfills some parameters in docId.

For example can I query Elasticsearch like this:

POST similarTerms/_search
{
    "fields": [
       "_id", "title"
    ]   ,
    "filter": {
    "query": {"match": {
       "title": doc[docId].title
    }}
    }, 
    "size": 30

}

I know I can fetch the document with docId and then I can prepare the above query, but can I avoid the network hop somehow as even milliseconds of time improvement is of great concern for my app.

Thanks

Upvotes: 3

Views: 2964

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

This is a text-book scenario for "more like this" api. Quote from the docs:

The more like this (mlt) API allows to get documents that are "like" a specified document. Here is an example:

$ curl -XGET 'http://localhost:9200/twitter/tweet/1/_mlt?mlt_fields=tag,content&min_doc_freq=1'

The API simply results in executing a search request with moreLikeThis query (http parameters match the parameters to the more_like_this query). This means that the body of the request can optionally include all the request body options in the search API (aggs, from/to and so on). Internally, the more like this API is equivalent to performing a boolean query of more_like_this_field queries, with one query per specified mlt_fields.

If you plan testing this (like I did) with one document only for test, make sure you also set min_term_freq=0 and min_doc_freq=0: GET /my_index/locations/1/_mlt?min_term_freq=0&min_doc_freq=0

Upvotes: 1

Related Questions