7

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.

4 Answers 4

18

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"
}}}
Sign up to request clarification or add additional context in comments.

1 Comment

This will be helpful, return only total number of records
9

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 the GET 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 a 404 Not Found if it doesn’t exist

Note: userid is the value of the _id field.

2 Comments

is it possible to translate that thanks to the node.js client?
2

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
}

2 Comments

First query return the record , but i dont want the record, and other is not exist in elasticsearch 5.* . Thanks
yeah i tried this query in older version, so not sure for latest version
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.