栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python操作elasticsearch

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python操作elasticsearch

from elasticsearch import Elasticsearch

# 删除索引
def delete_indices(es, my_index):
    if es.indices.exists(my_index):  # 确认删除再改为True
        es.indices.delete(index=my_index)   # 删除

# 创建索引示例1
def create_indices(es, my_index):
    # 创建
    es.indices.create(index=my_index)

# 查询索引内容
def search_index(es, my_index):
    body = {
        "query":{
            "match":{
                "name":"jgc"
            }
        }
    }
    res = es.search(index=my_index, body=body)
    # res = es.search(index=my_index, body=body, filter_path=['hits.hits']
    return res

if __name__ == "__main__":
    # 链接数据库
    es = Elasticsearch(['http://127.0.0.1:9200'])

    # 测试是否能链接
    print(es.ping())

    # 创建索引
    create_indices(es, "newlab")

    # 删除索引
    delete_indices(es, "newlab")

    # 查询
    print(search_index(es, "lab"))
    for item in res['hits']['hits']:
        print(item['_source'])
from elasticsearch import Elasticsearch

# 删除索引
def delete_indices(es, my_index):
    if es.indices.exists(my_index):  # 确认删除再改为True
        es.indices.delete(index=my_index)   # 删除

# 创建索引
def create_indices(es, my_index):
    mappings = {
        "mappings":{
            "properties": {
                "name": {
                    "type": "text"
                },
                "age": {
                    "type": "integer"
                }
            }
        }
    }
    # 创建索引时添加限制
    es.indices.create(index=my_index, body=mappings)

# 插入一条数据
def insert_index(es, my_index):
    body = {
        "name":"smr",
        "age":10
    }
    # 也可以在body里添加"_id"指定id,默认id为随机值
    es.index(index=my_index, body=body)

# 查询索引内容
def search_index(es, my_index):
    body = {
        "query":{
            "match_all":{
            }
        }
    }
    res = es.search(index=my_index, body=body)
    # res = es.search(index=my_index, body=body, filter_path=['hits.hits']
    return res

if __name__ == "__main__":
    # 链接数据库
    es = Elasticsearch(['http://127.0.0.1:9200'])

    # 测试是否能链接
    # print(es.ping())

    # 创建索引
    # create_indices(es, "test")

    # 插入一条数据
    # insert_index(es, "test")

    # 查询
    print(search_index(es, "test"))
    # for item in res['hits']['hits']:
    #     print(item['_source'])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/350176.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号