iurti
iurti

Reputation: 167

can terms lookup mechanism query by other field but id?

here is elasticsearch official website about terms: https://www.elastic.co/guide/en/elasticsearch/reference/2.1/query-dsl-terms-query.html

As we can see, if we want to do terms lookup mechanism query, we should use command like this:

curl -XGET localhost:9200/tweets/_search -d '{
  "query" : {
    "terms" : {
      "user" : {
        "index" : "users",
        "type" : "user",
        "id" : "2",
        "path" : "followers"
      }
    }
  }
}'

But what if i want to do query by other field of users. Assume that users has some other fields such as name and can i use terms lookup mechanism finding the tweets by giving users name but not id. I have tried to use command like this:

curl -XGET localhost:9200/tweets/_search -d '{
  "query" : {
    "terms" : {
      "user" : {
        "index" : "users",
        "type" : "user",
        "name" : "Jane",
        "path" : "followers"
      }
    }
  }
}'  

but it occurs error. Looking forward to your help. Thank you!

Upvotes: 3

Views: 6130

Answers (2)

Val
Val

Reputation: 217254

The terms lookup mechanism is basically a built-in optimization to not have to make two queries to JOIN two indices, i.e. one in index A to get the ids to lookup and a second to fetch the documents with those ids in index B.

In contrary to SQL, such a JOIN can only work on the id field since this is the only way to uniquely retrieve a document from Elasticsearch via a GET call, which is exactly what Elasticsearch will do in the terms lookup.

So to answer your question, the terms lookup mechanism will not work on any other field than the id field since the first document to be retrieved must be unique. In your case, ES would not know how to fetch the document for the user with name Jane since name is just a field present in the user document, but in no way a unique identifier for user Jane.

Upvotes: 7

bittusarkar
bittusarkar

Reputation: 6357

I think you did not understand exactly how this works. Terms lookup query works by reading values from a field of a document with the given id. In this case, you are trying to match the value of field user in tweets index with values of field followers in document with id "2" present in users index and user type.

If you want to read from any other field then simply mention that in "path".

What you mainly need to understand is that the lookup values are all fetched from a field of a single document and not multiple documents.

Upvotes: 5

Related Questions