python操作ES

建立链接

1
2
3
4
5
6
7
8
9
10
11
12
from elasticsearch import Elasticsearch
import json
 
es = Elasticsearch(
    ['localhost:9200'],
    # 启动前嗅探es集群服务器
    # sniff_on_start=True,
    # es集群服务器结点连接异常时是否刷新es节点信息
    # sniff_on_connection_fail=True,
    # 每60秒刷新节点信息
    # sniffer_timeout=60
)

 

创建索引

复制代码
# 创建索引
index_mapping = {
    "mappings": {
        "properties": {
            "name": {
                "type": "text"
            },
            "sex": {
                "type": "test"
            },
        "age": {
                "type": "integer"
            }
        "school": {
                "type": "text"
            }

        }
    }
}
if es.indices.exists(index='index') is not True:
  rew = es.indices.create(index='index', body=index_mapping)
  print("该索引创建成功")
else:
  print("该索引已存在")
View Code 
复制代码
1
2
3
4
5
6
7
# 在创建索引时忽略由 IndexAlreadyExistsException 引起的 400 已经存在
rs = es.indices.create(index='test', ignore=400)
print(json.dumps(rs, indent=2, ensure_ascii=False))
 
# 没有这样的索引 404  400 已删除
rs = es.indices.delete(index='test', ignore=[400, 404])
print(json.dumps(rs, indent=2, ensure_ascii=False))

一、插入

复制代码
# 插入单条
body = {
    'name': '张三',
    'sex': 'man',
    'age': 10,
    'school': '清华'
}

# 插入多条
bodys = [
    {
     "name":  "python",
     "addr": "深圳",
     "age": 18,
     "time": 12,
    },
    {
        "name": "深圳",
        "addr": "北京",
        "age": 20,
        "time": 100,
    },
    {
        "name":  "c",
        "addr": "香港",
        "age": 11,
        "time": 1300,
    },
    {
        "name":  "ios",
        "addr": "美国",
        "age": 8,
        "time": 120,
    },
    {
        "name":  "呼和浩特",
        "addr": "澳大利亚",
        "age": 1,
        "time": 111,
    },
    {
        "name":  "清河",
        "addr": "菲律宾",
        "age": 15,
        "time": 50,
    },


]
for body in bodys:
    # 增加
    rs = es.index(index='index', doc_type='type', body=body)
View Code
复制代码

二、查询

复制代码
# 查找
# rs = es.get(index='index', doc_type='type', id='qCbY4H0B8m4STfI58yWM')

# 只需要获取_id数据,多个条件用逗号隔开
rs = es.search(index='index', doc_type='type', filter_path=["hits.hits._id"])

# 获取所有数据
rs = es.search(index="index", doc_type="type", filter_path=["hits.hits._*"])

print(json.dumps(rs, indent=2, ensure_ascii=False))
View Code
复制代码

三、更新

1
2
# 更新
rs = es.update(index='index', doc_type='type', id='qSbY4H0B8m4STfI58yWO', body=body)

四、删除

1
2
# 删除
es.delete(index='index', doc_type='type', id='pCZP4H0B8m4STfI5_CU6')
posted @   长乐未央丫  阅读(296)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示