Reputation: 1263
I want to check if a document with specific field value does exist or not in elasticsearch.
I have gone through internet but only found how to check if a field exists or not.
My Index/Type is
/twitter/user
username is one field in document.
I want to check if username="xyz"
exists or not in this Type.
Upvotes: 7
Views: 28741
Reputation: 411
From the documentation:
If all you want to do is to check whether a document exists—you’re not interested in the content at all—then use the
HEAD
method instead of theGET
method.HEAD
requests don’t return a body, just HTTP headers:
curl -i -XHEAD http://localhost:9200/twitter/user/userid
Elasticsearch will return a
200 OK
status code if the document exists ... and a404 Not Found
if it doesn’t exist
Note: userid
is the value of the _id
field.
Upvotes: 9
Reputation: 1195
You can use term query with size 0. See below query for reference:
POST twitter/user/_search
{
"query": {
"term": {
"username": "xyz"
}
},
"size" : 0
}
Response:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0,
"hits": []
}
}
You will get total document count in hits.total and then you can check for count > 0
Upvotes: 2
Reputation: 4800
You can query with size 0
. total
value will give you an idea that doc exists or not.
GET /twitter/user/_search
{"size": 0,
"query": {"match": {
"username": "xyz"
}}}
Edited --
_count api can be used as well.
GET /twitter/user/_count
{ "query": {"match": {
"username": "xyz"
}}}
Upvotes: 18
Reputation: 15490
simply search the document, if it exists it will return result otherwise not
http://127.0.0.1:9200/twitter/user/_search?q=username:xyz
and the exact what are you looking for is
http://127.0.0.1:9200/twitter/user/_search/exists?q=username:xyz
it will return exists true
or false
{
"exists": false
}
Upvotes: 2