Elasticsearch Elasticsearch Find Document by Field Value

By Opster Team - May 2023

Updated: May 22, 2023

| 2 min read

Quick links

Elasticsearch: Find Document by Field Value

Introduction

Searching for documents in Elasticsearch based on specific field values is a common requirement in many applications. In this article, we will discuss various methods to find documents by field value using the Query DSL and provide examples for each method.

Methods to find documents by field value using the Query DSL

1. Match Query

The match query is used to search for documents containing the specified field value. It is a standard query for full-text search and works well for searching text fields.

Example:

To search for documents with the field “title” containing the value “Elasticsearch”:

GET /my_index/_search
{
"query": {
"match": {
"title": "Elasticsearch"
}
}
}

2. Term Query

The term query is used to search for documents containing the exact term specified in the field. It is suitable for searching keyword fields or fields with exact values.

Example:

To search for documents with the field “status” containing the exact value “published”:

GET /my_index/_search
{
"query": {
"term": {
"status": "published"
}
}
}

3. Range Query

The range query is used to search for documents with field values within a specified range. It is useful for searching numeric or date fields.

Example:

To search for documents with the field “price” containing a value between 10 and 50:

GET /my_index/_search
{
"query": {
"range": {
"price": {
"gte": 10,
"lte": 50
}
}
}
}

4. Bool Query

The bool query is used to combine multiple queries using Boolean logic. It allows you to search for documents based on multiple field values using the “must”, “should”, and “must_not” clauses.

Example:

To search for documents with the field “title” containing the value “Elasticsearch” and the field “status” containing the exact value “published”:

GET /my_index/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"title": "Elasticsearch"
}
},
{
"term": {
"status": "published"
}
}
]
}
}
}

5. Wildcard Query

The wildcard query is used to search for documents containing field values that match a specified pattern. It uses the “*” and “?” wildcard characters to represent any number of characters or a single character, respectively.

Example:

To search for documents with the field “title” containing the value “Elasticsearch” followed by any number of characters:

GET /my_index/_search
{
"query": {
"wildcard": {
"title": "Elasticsearch*"
}
}
}

Conclusion

In this article, we discussed various methods to find documents in Elasticsearch based on specific field values. By using the appropriate query type, you can efficiently search for documents that match your criteria. Remember to consider the type of field and the nature of the data when choosing the right query for your use case.