SoFunction
Updated on 2025-04-28

Python calls Elasticsearch to perform addition, deletion, modification and search operations

Basic Operation

1. Connect to the Elasticsearch database

First connect to the Elasticsearch database and then create a custom index

from elasticsearch import Elasticsearch
import random
from elasticsearch import helpers

# Connect to the local Elasticsearch servicees = Elasticsearch(hosts=["http://localhost:9200"])
index_name = "my_index"

# Create an index with an index named "my_index"if (index=index_name):  # If the index exists, delete    (index=index_name)
(index=index_name)  # Create a new index

2. Add random data

Here we create a random data item, including value_num and value_choice items,

# Add random data itemsadd_value_list: list = []
for _ in range(1000):
    num = (1, 100)
    add_value_list.append({
        "_index": index_name,  # Notice!  Parameters determine which index to insert into        "value_num": (1, 100),
        "value_choice": ["c1", 'c2', 'c3'][(0, 2)],
    })
# Insert data in batches(es, add_value_list)

3. Query operation

# Query operation_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # >= 40
                "lte": 60  # <= 60
            }
        }
    },
    "size": 20,  # Query 20 items}
response = (index=index_name, body=_body_query)
# Print the query resultsfor _hit in response["hits"]["hits"]:
    _value = _hit['_source']
    print("value_num:", _value["value_num"], " value_choice:", _value['value_choice'])

4. Update data items

Here, we will reassign the data from the query data through the document ID and modified data.

# Update operationfor _hit in response["hits"]["hits"]:
    update_body = {"doc": {
        "value_choice": "c4",  # Update the value_choice field to c4    }}
    res = (index=index_name, id=_hit['_id'], body=update_body)

5. Delete data items

# Delete operationfor _hit in response["hits"]["hits"]:
    res = (index=index_name, id=_hit['_id'])

More query methods

1. Query all data

_body_query = {
    "query":{
        "match_all":{}
    }
}

2. Query for a certain value/string: term, match

Match will perform multiple term operations, and the term operation accuracy will be higher

_body_query = {
    "query": {
        "match": {
            "value_choice": "c1"
        }
    }
}
_body_query = {
    "query": {
        "term": {
            "value_choice": "c1"
        }
    }
}

3. If there is one match among multiple options, find it out: terms

_body_query = {
    "query": {
        "terms": {
            "value_choice": ["c1", "c2"],
        }
    }
}

4. Numerical range query: range

Query data >=40 and <=60

_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # >= 40
                "lte": 60  # <= 60
            }
        }
    }
}

5. Multiple conditions trigger bool at the same time

Boolean query can query multiple conditions at the same time, also known as a combination query. When constructing the dictionary data of the query, query is followed by bool, and then the judgment conditions of bool. There are the following:

  • filter: filter
  • Must: Similar to and, all conditions need to be met
  • Should: Similar to or, as long as one can satisfy
  • Must_not: Necessary is not satisfied

After writing the judgment conditions, follow the specific details of the query operation in the list of the judgment conditions.

_body_query = {
    "query": {
        "bool": {
            "should": [
                {
                    "match": {"value_choice": "c1"} # value_choice = "c1"
                },
                {
                    "range": {"value_num": {"lte": 50}} # value_num <= 50
                }
            ]
        }
    },
}

6. Specify the number of return values ​​size

Just add the size keyword to the constructed dictionary

_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # >= 40
                "lte": 60  # <= 60
            }
        }
    },
    "size": 20,
}

7. Return to the specified column _source

_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # &gt;= 40
                "lte": 60  # &lt;= 60
            }
        }
    },
     "_source": ["value_num"] # Here specify the fields returned}

Complete sample program

from elasticsearch import Elasticsearch
import random
from elasticsearch import helpers

# Connect to the local Elasticsearch servicees = Elasticsearch(hosts=["http://localhost:9200"])
index_name = "my_index"

# Create an index with an index named "my_index"if (index=index_name):  # If the index exists, delete    (index=index_name)
(index=index_name)  # Create a new index
# Generate random dataadd_value_list: list = []
for _ in range(1000):
    num = (1, 100)
    add_value_list.append({
        "_index": index_name,  # Notice!  Parameters determine which index to insert into        "value_num": (1, 100),
        "value_choice": ["c1", 'c2', 'c3'][(0, 2)],
    })
# Insert data in batches(es, add_value_list)

# ================================================_body_query = {
    "query": {
        "range": {
            "value_num": {
                "gte": 40,  # &gt;= 40
                "lte": 60  # &lt;= 60
            }
        }
    },
    "size": 20,
}

response = (index=index_name, body=_body_query)  # Query 10 items# Print the query resultsfor _hit in response["hits"]["hits"]:
    _value = _hit['_source']
    print("value_num:", _value["value_num"], " value_choice:", _value['value_choice'])

# Update operationfor _hit in response["hits"]["hits"]:
    update_body = {"doc": {
        "value_choice": "c4",  # Update the value_choice field to c4    }}
    res = (index=index_name, id=_hit['_id'], body=update_body)

# Delete operationfor _hit in response["hits"]["hits"]:
    res = (index=index_name, id=_hit['_id'])

This is the article about python calling Elasticsearch to perform addition, deletion, modification and search operations. For more related python Elasticsearch to add, deletion, modification and search operations, please search for my previous articles or continue to browse the related articles below. I hope everyone will support me in the future!