使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

这篇具有很好参考价值的文章主要介绍了使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.添加索引

示例代码1:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    "mappings": {
        "properties": {
            "grade": {
                "type": "long"
            },
            "id": {
                "type": "long"
            },
            "name": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "sex": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "subject": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            }
        }
    }
}

# 创建索引
res = es.index(index="test_index", id=1, document=doc)
print(res)
print(res['result'])

# 创建索引
res2 = es.index(index='test_index2', document=doc)
print(res2)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

示例代码2:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    "mappings": {
        "properties": {
            "grade": {
                "type": "long"
            },
            "id": {
                "type": "long"
            },
            "name": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "sex": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "subject": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            }
        }
    }
}

# 创建索引
res = es.index(index="test_index", id=1, document=doc)
print(res)
print(res['result'])
print("*" * 100)

# 创建索引
res2 = es.index(index='test_index2', document=doc)
print(res2)
print(res2['result'])
print("*" * 100)

# 创建索引  res3运行两次会报错
res3 = es.indices.create(index="test_index3", body=doc)
print(res3)
# print(res3['result'])  # 注意:此行运行会报错
print("*" * 100)

# 创建索引  res4多次执行会报错
res4 = es.create(index='test_index4', id=1, document=doc)
print(res4)
print(res4['result'])

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

示例代码3:

from elasticsearch import Elasticsearch
from datetime import datetime


es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'author': 'dgw',
    'text': 'Elasticsearch: cool. bonsai cool.',
    'timestamp': datetime.now(),
}

res = es.index(index="test_index", id=1, document=doc)
print(res)
print(res['result'])

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

注意:对比上面几种建立索引的方法,是有一定区别的。根据响应结果可以看出:es. indices.create()方法是标准的创建索引的方法,其它几种方法在创建索引的同时也会生成一条数据,并且生成mapping不是我们自己定义的类型,分别如下图所示:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

2.查询索引

示例代码:

from elasticsearch import Elasticsearch
from datetime import datetime

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'author': 'dgw',
    'text': 'Elasticsearch: cool. bonsai cool.',
    'timestamp': datetime.now(),
}

# 创建索引
res = es.index(index="test_index", id=1, document=doc)
print(res)
print(res['result'])

# 查询数据
res2 = es.get(index="test_index", id=1)
print(res2)
print(res2['_source'])

es.indices.refresh(index="test_index")

query = {
    "match_all": {}
}
res3 = es.search(index='test_index', query=query)
print(res3)
print("Got %d Hits:" % res3['hits']['total']['value'])
for hit in res3['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

3.删除索引/数据

示例代码1:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="test_index"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="test_index")
else:
    print('test_index索引不存在!')

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

示例代码2:

from elasticsearch import Elasticsearch
import time

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'mappings': {
        'properties': {
            'name': {
                'type': 'text'
            },
            'id': {
                'type': 'integer'
            },
        }
    }
}

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="test_index"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="test_index")
else:
    print('索引不存在!可以创建')

# 创建索引
res = es.indices.create(index="test_index", body=doc)
print(res)
print("*" * 100)

# 添加数据
es.index(index="test_index", id='1', document={"name": "北京张三", "id": 1})
es.index(index="test_index", id='2', document={"name": "河北李四", "id": 2})
# 使用create时,当id已经存在时会报错
es.create(index="test_index", id="3", document={"name": "北京王五", "id": 3})
es.create(index="test_index", id='4', document={"name": "上海赵六", "id": 4})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 使用search查询数据
query = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res = es.search(index="test_index", body=query)
print(res)

# 删除指定id数据
res = es.delete(index="test_index", id=3)
print(res)

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果可能受影响,上面删除数据需要时间

# 使用search查询数据
query2 = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res2 = es.search(index="test_index", body=query2)
print(res2)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

4.判断索引是否存在

        为防止在创建索引的时候出现重复,产生错误,在创建之前最好判断一下索引是否存在。

示例代码:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://47.93.5.86:9200')
# print(es)

doc = {
    "mappings": {
        "properties": {
            "grade": {
                "type": "long"
            },
            "id": {
                "type": "long"
            },
            "name": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "sex": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "subject": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            }
        }
    }
}

# 创建索引
res = es.index(index="test_index", id=1, document=doc)
print(res)
print(res['result'])

# 判断索引是否存在
es_exist = es.exists(index="test_index", id=2)
print(es_exist)

# 判断索引是否存在
es_exist = es.indices.exists(index='test_index')
print(es_exist)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

5.添加数据

示例代码1:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'mappings': {
        'properties': {
            'name': {
                'type': 'text'
            },
            'id': {
                'type': 'integer'
            },
        }
    }
}

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="test_index"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="test_index")
else:
    print('索引不存在!可以创建')

# 创建索引
res = es.indices.create(index="test_index", body=doc)
print(res)
print("*" * 100)

# 添加数据
es.index(index="test_index", id='1', document={"name": "北京张三", "id": 1})
es.index(index="test_index", id='2', document={"name": "河北李四", "id": 2})

# 查询数据
res = es.get(index="test_index", id=1)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

示例代码2:

from elasticsearch import Elasticsearch
import time

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'mappings': {
        'properties': {
            'name': {
                'type': 'text'
            },
            'id': {
                'type': 'integer'
            },
        }
    }
}

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="test_index"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="test_index")
else:
    print('索引不存在!可以创建')

# 创建索引
res = es.indices.create(index="test_index", body=doc)
print(res)
print("*" * 100)

# 添加数据
# index可以自动生成id
es.index(index="test_index", id='1', document={"name": "北京张三", "id": 1})
es.index(index="test_index", id='2', document={"name": "河北李四", "id": 2})
# 使用create时,当id已经存在时会报错,id唯一标识,当id不存在时也报错
es.create(index="test_index", id="3", document={"name": "北京王五", "id": 3})
es.create(index="test_index", id='4', document={"name": "上海赵六", "id": 4})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 使用search查询数据
query = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res = es.search(index="test_index", body=query)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

6.更新数据

全局更新:在 Elasticsearch 中,通过指定文档的 _id, 使用 Elasticsearch 自带的 index api 可以实现插入一条 document , 如果该 _id 已存在,将直接更新该 document。通过这种方法修改,因为是 reindex 过程,所以当数据量或者 document 很大的时候,效率非常的低

示例代码1:

from elasticsearch import Elasticsearch
import time

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'mappings': {
        'properties': {
            'name': {
                'type': 'text'
            },
            'id': {
                'type': 'integer'
            },
        }
    }
}

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="test_index"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="test_index")
else:
    print('索引不存在!可以创建')

# 创建索引
res = es.indices.create(index="test_index", body=doc)
print(res)
print("*" * 100)

# 添加数据
es.index(index="test_index", id='1', document={"name": "北京张三", "id": 1})
es.index(index="test_index", id='2', document={"name": "河北李四", "id": 2})
es.index(index="test_index", id='3', document={"name": "北京王五", "id": 3})
es.index(index="test_index", id='4', document={"name": "上海赵六", "id": 4})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 使用search查询数据
query = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res = es.search(index="test_index", body=query)
print(res)
print("*" * 100)

# 更新数据  如果当前id存在则为更新,若不存在则为新增
# 注意:当id存在时的更新为整体替换,而不是局部替换
es.index(index="test_index", id='4', document={"name": "山西王五"})
es.index(index="test_index", id='5', document={"name": "山东周八", "id": 888})
es.index(index="test_index", id='6', document={"name": "上海孙七", "id": 6})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 查询数据
query2 = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res2 = es.search(index="test_index", body=query2)
print(res2)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

局部更新:Elasticsearch 中的 update API 支持根据用户提供的脚本去实现更新。Update 更新操作允许 ES 获得某个指定的文档,可以通过脚本等操作对该文档进行更新。可以把它看成是先删除再索引的原子操作,只是省略了返回的过程,这样即节省了来回传输的网络流量,也避免了中间时间造成的文档修改冲突。

示例代码2:

from elasticsearch import Elasticsearch
import time

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'mappings': {
        'properties': {
            'name': {
                'type': 'text'
            },
            'id': {
                'type': 'integer'
            },
        }
    }
}

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="test_index"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="test_index")
else:
    print('索引不存在!可以创建')

# 创建索引
res = es.indices.create(index="test_index", body=doc)
print(res)
print("*" * 100)

# 添加数据
es.index(index="test_index", id='1', document={"name": "北京张三", "id": 1})
es.index(index="test_index", id='2', document={"name": "河北李四", "id": 2})
es.index(index="test_index", id='3', document={"name": "北京王五", "id": 3})
es.index(index="test_index", id='4', document={"name": "上海赵六", "id": 4})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 使用search查询数据
query = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res = es.search(index="test_index", body=query)
print(res)
print("*" * 100)

# 更新数据 局部更新数据 如果当前id存在则为局部更新,若不存在则报错
es.update(index="test_index", id='2', doc={"id": 222})
es.update(index="test_index", id='4', doc={"name": "山西王五"})
es.update(index="test_index", id='3', body={"doc": {"id": "333"}})  # 注意这儿和上面写法的不同
# 当update更新的文档id不存在时会报错
# es.update(index="test_index", id='5', doc={"name": "山东周八", "id": 6})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 查询数据
query2 = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res2 = es.search(index="test_index", body=query2)
print(res2)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

批量更新:ES 有提供批量操作的接口 bulk

示例代码:

from elasticsearch import Elasticsearch
from elasticsearch import helpers
import time

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'mappings': {
        'properties': {
            'name': {
                'type': 'text'
            },
            'id': {
                'type': 'integer'
            },
        }
    }
}

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="test_index"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="test_index")
else:
    print('索引不存在!可以创建')

# 创建索引
res = es.indices.create(index="test_index", body=doc)
print(res)
print("*" * 100)

# 添加数据
es.index(index="test_index", id='1', document={"name": "北京张三", "id": 1})
es.index(index="test_index", id='2', document={"name": "河北李四", "id": 2})
es.index(index="test_index", id='3', document={"name": "北京王五", "id": 3})
es.index(index="test_index", id='4', document={"name": "上海赵六", "id": 4})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 使用search查询数据
query = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res = es.search(index="test_index", body=query)
print(res)
print("*" * 100)

# 需要更新的词典
dic_lst = [{"_index": "test_index", "_id": 2, "_type": "_doc", "_op_type": "update", "doc": {"id": 222}},
           {"_index": "test_index", "_id": 3, "_type": "_doc", "_op_type": "update",
            "doc": {"name": "天津王五", "id": 333}},
           {"_index": "test_index", "_id": 4, "_type": "_doc", "_op_type": "update", "doc": {"name": "山西王五"}}
           ]

# 批量更新数据,当id存在时是局部更新,当id不存在时报错
actions = []
for dic in dic_lst:
    actions.append(dic)

if actions:
    helpers.bulk(es, actions)

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 查询数据
query2 = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res2 = es.search(index="test_index", body=query2)
print(res2)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

7.查询数据

示例代码:

from elasticsearch import Elasticsearch
import time

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    'mappings': {
        'properties': {
            'name': {
                'type': 'text'
            },
            'id': {
                'type': 'integer'
            },
        }
    }
}

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="test_index"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="test_index")
else:
    print('索引不存在!可以创建')

# 创建索引
res = es.indices.create(index="test_index", body=doc)
print(res)
print("*" * 100)

# 添加数据
es.index(index="test_index", id='1', document={"name": "北京张三", "id": 1})
es.index(index="test_index", id='2', document={"name": "河北李四", "id": 2})
es.index(index="test_index", id='3', document={"name": "北京王五", "id": 3})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 查询数据
# 使用get查询数据,按id来查询
res = es.get(index="test_index", id=1)
print(res)
print("*" * 100)

# 使用search查询数据
query1 = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 10
}
res2 = es.search(index="test_index", body=query1)
print(res2)
print("*" * 100)

# 精确查找term
query2 = {
    "query": {
        "term": {
            "name": {
                "value": "北"
            }
        }
    }
}
res2 = es.search(index="test_index", body=query2)
print(res2)
print("*" * 100)

# 精确查找terms
query3 = {
    "query": {
        "terms": {
            "name": [
                "张",
                "李"
            ]
        }
    }
}
res3 = es.search(index="test_index", body=query3)
print(res3)
print("*" * 100)

# 模糊查找match
query4 = {
    "query": {
        "match": {
            "name": "京"
        }
    }
}
res = es.search(index="test_index", body=query4)
print(res)
print("*" * 100)

# 查询id和name包含
query5 = {
    "query": {
        "multi_match": {
            "query": "张三",
            "fields": ["name"]
        }
    }
}
res = es.search(index="test_index", body=query5)
print(res)
print("*" * 100)

# 搜索出id为1或者2的所有数据
query6 = {
    "query": {
        "ids": {
            "type": "_doc",
            "values": ["1", "2"]
        }
    }
}
res = es.search(index="test_index", body=query6)
print(res)
print("*" * 100)

运行结果:

test_index索引存在,即将删除
{'acknowledged': True, 'shards_acknowledged': True, 'index': 'test_index'}
****************************************************************************************************
{'_index': 'test_index', '_type': '_doc', '_id': '1', '_version': 1, '_seq_no': 0, '_primary_term': 1, 'found': True, '_source': {'name': '北京张三', 'id': 1}}
****************************************************************************************************
{'took': 0, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 3, 'relation': 'eq'}, 'max_score': 1.0, 'hits': [{'_index': 'test_index', '_type': '_doc', '_id': '1', '_score': 1.0, '_source': {'name': '北京张三', 'id': 1}}, {'_index': 'test_index', '_type': '_doc', '_id': '2', '_score': 1.0, '_source': {'name': '河北李四', 'id': 2}}, {'_index': 'test_index', '_type': '_doc', '_id': '3', '_score': 1.0, '_source': {'name': '北京王五', 'id': 3}}]}}
****************************************************************************************************
{'took': 0, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 3, 'relation': 'eq'}, 'max_score': 0.13353139, 'hits': [{'_index': 'test_index', '_type': '_doc', '_id': '1', '_score': 0.13353139, '_source': {'name': '北京张三', 'id': 1}}, {'_index': 'test_index', '_type': '_doc', '_id': '2', '_score': 0.13353139, '_source': {'name': '河北李四', 'id': 2}}, {'_index': 'test_index', '_type': '_doc', '_id': '3', '_score': 0.13353139, '_source': {'name': '北京王五', 'id': 3}}]}}
****************************************************************************************************
{'took': 0, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 2, 'relation': 'eq'}, 'max_score': 1.0, 'hits': [{'_index': 'test_index', '_type': '_doc', '_id': '1', '_score': 1.0, '_source': {'name': '北京张三', 'id': 1}}, {'_index': 'test_index', '_type': '_doc', '_id': '2', '_score': 1.0, '_source': {'name': '河北李四', 'id': 2}}]}}
****************************************************************************************************
{'took': 0, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 2, 'relation': 'eq'}, 'max_score': 0.4700036, 'hits': [{'_index': 'test_index', '_type': '_doc', '_id': '1', '_score': 0.4700036, '_source': {'name': '北京张三', 'id': 1}}, {'_index': 'test_index', '_type': '_doc', '_id': '3', '_score': 0.4700036, '_source': {'name': '北京王五', 'id': 3}}]}}
****************************************************************************************************
{'took': 0, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 1, 'relation': 'eq'}, 'max_score': 1.9616582, 'hits': [{'_index': 'test_index', '_type': '_doc', '_id': '1', '_score': 1.9616582, '_source': {'name': '北京张三', 'id': 1}}]}}
****************************************************************************************************
{'took': 0, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 2, 'relation': 'eq'}, 'max_score': 1.0, 'hits': [{'_index': 'test_index', '_type': '_doc', '_id': '1', '_score': 1.0, '_source': {'name': '北京张三', 'id': 1}}, {'_index': 'test_index', '_type': '_doc', '_id': '2', '_score': 1.0, '_source': {'name': '河北李四', 'id': 2}}]}}
****************************************************************************************************

8.复合查询数据

示例代码:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

query = {
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "name": {
                            "value": "张"
                        }
                    }
                },
                {
                    "term": {
                        "id": {
                            "value": "1"
                        }
                    }
                }
            ]
        }
    }
}

res = es.search(index="test_index", body=query)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

9.切片查询数据

示例代码:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

query = {
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 2
}

res = es.search(index="test_index", body=query)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

10.范围查询数据

示例代码:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

query = {
    "query": {
        "range": {
            "id": {
                "gte": 1,
                "lte": 2
            }
        }
    }
}

res = es.search(index="test_index", body=query)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

11.前缀查询数据

示例代码:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

# 查询前缀为“张”的数据。注意:这个要看分词后的前缀
query = {
    "query": {
        "prefix": {
            "name": {
                "value": "张"
            }
        }
    }
}

res = es.search(index="test_index", body=query)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

12.通配符查询

wildcard查询:会对查询条件进行分词。还可以使用通配符?(任意单个字符)和*(0个或多个字符)

示例代码:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

query = {
    "query": {
        "wildcard": {
            "name": {
                "value": "三"
            }
        }
    }
}

res = es.search(index="test_index", body=query)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

13.正则匹配查询

示例代码:

from elasticsearch import Elasticsearch
import time

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

doc = {
    "mappings": {
        "properties": {
            "grade": {
                "type": "long"
            },
            "id": {
                "type": "long"
            },
            "name": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "sex": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            }
        }
    }
}

# 判断索引是否存在,存在则删除索引
if es.indices.exists(index="student_info"):
    print('test_index索引存在,即将删除')
    es.indices.delete(index="student_info")
else:
    print('索引不存在!可以创建')

# 创建索引
res = es.indices.create(index="student_info", body=doc)
print(res)
print("*" * 100)

# 添加数据
es.index(index="student_info", id='1', document={"name": "北京张三", "id": 1, "sex": "男", "grade": 99})
es.index(index="student_info", id='2', document={"name": "河北李四", "id": 2, "sex": "男", "grade": 98})

time.sleep(1)  # 如果不加时间停顿的话,下面查询的结果为空,上面添加数据需要时间

# 查询数据
res = es.get(index="student_info", id=1)
print(res)

# 正则查询
query2 = {
    "query": {
        "regexp": {
            "name.keyword": "(.*?)三(.*?)"
        }
    }
}
res = es.search(index="student_info", body=query2)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)

14.查询数据排序

示例代码:

from elasticsearch import Elasticsearch

es = Elasticsearch(hosts='http://127.0.0.1:9200')
# print(es)

query = {
    "query": {
        "match_all": {}
    },
    "sort": [
        {
            "id": {
                "order": "desc"  # asc升序,desc降序
            }
        }
    ]
}

res = es.search(index="test_index", body=query)
print(res)

运行结果:

使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)文章来源地址https://www.toymoban.com/news/detail-510173.html

到了这里,关于使用python在es中基本操作详解(添加索引、查询索引、删除索引、判断索引是否存在、添加数据、更新数据、查询数据)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 太强了!利用 Python 连接 ES 查询索引某个字段命中数的脚本!

    当我们在工作中,如果频繁查询 Elasticsearch 某个索引中的某个字段命中的记录数量时,可以通过 Python 的 Elasticsearch 库来查询,从而提升工作效率。 代码大致思路如下: 第一步 :从 elasticsearch 模块导入 Elasticsearch 类,该类是用来连接和操作 Elasticsearch 第二步 :安装 Elastics

    2024年02月03日
    浏览(35)
  • Python连接Elasticsearch查询索引字段命中数详解

    📚 个人网站:ipengtao.com Elasticsearch是一款强大的搜索和分析引擎,通过其RESTful API,可以方便地与其交互。本篇文章将深入探讨如何使用Python连接Elasticsearch,并通过查询索引某个字段的命中数来实现数据统计的目的。将介绍基础的Elasticsearch查询、高级的聚合查询以及一些常

    2024年02月04日
    浏览(39)
  • (十)ElasticSearch高级使用【别名,重建索引,refresh操作,高亮查询,查询建议】

    在开发中,随着业务需求的迭代,较⽼的业务逻辑就要⾯临更新甚⾄是重构,⽽对于es来说,为了 适应新的业务逻辑,可能就要对原有的索引做⼀些修改,⽐如对某些字段做调整,甚⾄是重建索 引。⽽做这些操作的时候,可能会对业务造成影响,甚⾄是停机调整等问题。由此

    2024年02月02日
    浏览(48)
  • 【ElasticSearch】ElasticSearch Java API的使用——常用索引、文档、查询操作(二)

    Elaticsearch ,简称为es,es是一个开源的 高扩展 的 分布式全文检索引擎 ,它可以近乎 实时的存储 、 检索数据; 本身扩展性很好,可以扩展到上百台服务器,处理PB级别(大数据时代)的数据。es也使用java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的 目的

    2024年01月16日
    浏览(57)
  • Es 索引查询与删除

    1、 #删除单个索引 2、#删除多个指定索引,中间用逗号隔开 3、#模糊匹配删除 4、#使用通配符,删除所有的索引 5、#获取当前索引 6、如果存储不够可以设置定时删除,下面是保留3天的日志 以下是定时删除脚本:

    2024年02月11日
    浏览(28)
  • 【Elasticsearch】ES精确查询和范围查询,ES时间字段排序实例,ES倒排索引介绍

    termQuery matchQuery 模糊查询 multiMatchQuery 多个字段模糊查询 如果时间字段写入时用的类型是Text,可以用“时间字段.keyword”来处理 #查询前传入分页参数 #分页后拿到总记录数 把文档D对应到的映射转换为到文档ID的映射,每个都对应着一系列的文档,这些文

    2024年02月15日
    浏览(91)
  • ES查询多个索引,但是某些索引的name不同

    参考: https://blog.csdn.net/qq_37147750/article/details/111319151 背景: 目前有四个索引index, 对于这四个index他们的字段并不完全相同,要支持筛选。 目前的问题是,其中有两个索引要先根据条件筛选一遍。后续的筛选根据这次的结果做基础。 但是这两个索引的筛选条件也不一样。 相

    2024年02月13日
    浏览(30)
  • ES命令行查询es集群的状态、分片、索引

    查看es集群状态 查看es分片信息 查看es索引 查看ES索引 本文参考:https://www.cnblogs.com/expiator/p/14847705.html

    2024年02月12日
    浏览(29)
  • ES查询索引字段的分词结果

    一、_termvectors  1、查看文档中某一个字段的分词结果 GET /{index}/{type}/{_id}/_termvectors?fields=[field] 2、样例: text的值为:https://www.b4d99.com/html/202204/45672.html 得到的结果: 二、_analyze 1、语法 2、样例: text的值为:https://www.b4d99.com/html/202204/45672.html 得到的结果:

    2024年02月11日
    浏览(45)
  • 如何使用索引加速 SQL 查询 [Python 版]

    推荐:使用 NSDT场景编辑器助你快速搭建可二次编辑器的3D应用场景 假设您正在筛选一本书的页面。而且您希望更快地找到所需的信息。你是怎么做到的?好吧,您可能会查找术语索引,然后跳转到引用特定术语的页面。SQL 中的索引的工作方式与书籍 中的索引 类似。 在大多

    2024年02月13日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包