poissonsearch-py基础操作:10个常用Elasticsearch API调用示例
poissonsearch-py基础操作10个常用Elasticsearch API调用示例【免费下载链接】poissonsearch-pyOfficial Python client for Elasticsearch.The original name is elasticsearch-py, and the name is changed to poissonsearch-py for self-maintenance.项目地址: https://gitcode.com/openeuler/poissonsearch-py前往项目官网免费下载https://ar.openeuler.org/ar/想要在Python项目中轻松操作Elasticsearch吗poissonsearch-py作为Elasticsearch的官方Python客户端库提供了简洁高效的API接口让开发者能够快速上手Elasticsearch的各种操作。无论你是搜索功能的新手还是经验丰富的开发者掌握这10个常用API调用将大幅提升你的开发效率。 1. 安装与连接配置首先让我们从安装开始。poissonsearch-py可以通过pip轻松安装pip install elasticsearch注意虽然项目名称为poissonsearch-py但在Python包管理中仍然使用elasticsearch这个名称进行安装。连接Elasticsearch集群非常简单from elasticsearch import Elasticsearch # 连接到本地Elasticsearch es Elasticsearch() # 连接到远程集群 es Elasticsearch( [localhost:9200, otherhost:9200], http_auth(user, password), schemehttps, port443, ) 2. 创建索引与映射索引是Elasticsearch中存储数据的基本单位。使用poissonsearch-py可以轻松创建索引并定义字段映射# 创建索引 es.indices.create( indexmy_index, body{ settings: { number_of_shards: 3, number_of_replicas: 2 }, mappings: { properties: { title: {type: text}, content: {type: text}, timestamp: {type: date}, views: {type: integer} } } } ) 3. 文档索引操作索引文档是将数据存储到Elasticsearch的核心操作# 索引单条文档 document { title: Elasticsearch入门指南, content: Elasticsearch是一个基于Lucene的搜索服务器, timestamp: 2023-10-01T10:00:00, views: 1500 } # 指定ID索引 es.index(indexmy_index, id1, bodydocument) # 自动生成ID索引 response es.index(indexmy_index, bodydocument) doc_id response[_id] # 获取自动生成的文档ID 4. 基础搜索查询搜索是Elasticsearch的核心功能poissonsearch-py提供了灵活的搜索接口# 简单全文搜索 response es.search( indexmy_index, body{ query: { match: { content: Elasticsearch } } } ) # 获取搜索结果 for hit in response[hits][hits]: print(f文档ID: {hit[_id]}) print(f文档内容: {hit[_source]}) print(f相关性分数: {hit[_score]}) 5. 精确查询与过滤除了全文搜索你还可以进行精确查询# 精确匹配查询 response es.search( indexmy_index, body{ query: { term: { views: 1500 } } } ) # 范围查询 response es.search( indexmy_index, body{ query: { range: { timestamp: { gte: 2023-01-01, lte: 2023-12-31 } } } } ) 6. 聚合分析功能Elasticsearch强大的聚合功能可以帮助你分析数据# 按字段分组统计 response es.search( indexmy_index, body{ size: 0, # 不返回具体文档 aggs: { views_by_title: { terms: { field: title.keyword, size: 10 } } } } ) # 获取聚合结果 buckets response[aggregations][views_by_title][buckets] for bucket in buckets: print(f标题: {bucket[key]}, 数量: {bucket[doc_count]}) 7. 批量操作优化性能批量操作可以显著提升数据处理效率from elasticsearch import helpers # 批量索引文档 actions [ { _index: my_index, _source: { title: f文档{i}, content: f这是第{i}个文档的内容, views: i * 100 } } for i in range(100) ] # 执行批量操作 helpers.bulk(es, actions) 8. 更新与删除文档文档的更新和删除操作同样简单# 更新文档 es.update( indexmy_index, id1, body{ doc: { views: 2000, updated_at: 2023-10-02T14:30:00 } } ) # 删除文档 es.delete(indexmy_index, id1) # 按查询删除 es.delete_by_query( indexmy_index, body{ query: { range: { views: {lt: 100} } } } ) 9. 索引管理与监控管理索引状态和获取集群信息# 获取索引信息 index_info es.indices.get(indexmy_index) print(f索引设置: {index_info[my_index][settings]}) # 获取索引统计信息 stats es.indices.stats(indexmy_index) print(f文档总数: {stats[indices][my_index][total][docs][count]}) # 检查索引是否存在 if es.indices.exists(indexmy_index): print(索引存在)️ 10. 错误处理与重试机制在生产环境中良好的错误处理至关重要from elasticsearch import Elasticsearch, ConnectionError, NotFoundError try: # 尝试执行操作 response es.get(indexmy_index, idnon_existent_id) except NotFoundError as e: print(f文档不存在: {e.info}) except ConnectionError as e: print(f连接错误: {e.info}) # 可以在这里添加重试逻辑 except Exception as e: print(f其他错误: {str(e)}) 实用技巧与最佳实践连接池管理# 配置连接池 es Elasticsearch( [node1:9200, node2:9200], sniff_on_startTrue, # 启动时发现节点 sniff_on_connection_failTrue, # 连接失败时发现节点 sniffer_timeout60 # 60秒刷新节点列表 )异步客户端使用poissonsearch-py还提供了异步客户端适用于异步应用from elasticsearch import AsyncElasticsearch import asyncio async def main(): es AsyncElasticsearch() # 异步操作 response await es.search(indexmy_index, body{query: {match_all: {}}}) await es.close() asyncio.run(main()) 总结通过这10个常用API调用示例你已经掌握了poissonsearch-py的基础操作。这个强大的Python客户端库让Elasticsearch的集成变得异常简单。记住这些关键点连接配置灵活配置多节点连接和认证CRUD操作完整的文档生命周期管理搜索查询支持各种复杂的查询需求聚合分析强大的数据统计和分析能力批量处理优化性能的批量操作错误处理健壮的错误处理机制现在你已经具备了使用poissonsearch-py进行Elasticsearch开发的基础知识。继续探索官方文档中的高级功能如地理空间搜索、脚本查询、索引别名等让你的搜索应用更加强大提示在实际项目中建议将Elasticsearch连接配置和常用操作封装成独立的服务类提高代码的可维护性和复用性。【免费下载链接】poissonsearch-pyOfficial Python client for Elasticsearch.The original name is elasticsearch-py, and the name is changed to poissonsearch-py for self-maintenance.项目地址: https://gitcode.com/openeuler/poissonsearch-py创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考