当前位置: 代码网 > it编程>前端脚本>Python > python ES连接服务器的方法详解

python ES连接服务器的方法详解

2024年10月25日 Python 我要评论
连接elasticsearch(es)服务器是进行数据搜索和分析的常用操作。elasticsearch是一个基于lucene的搜索引擎,提供了restful api来进行索引、搜索和管理数据。以下是一

连接elasticsearch(es)服务器是进行数据搜索和分析的常用操作。elasticsearch是一个基于lucene的搜索引擎,提供了restful api来进行索引、搜索和管理数据。

以下是一个详细的python代码示例,展示如何连接到elasticsearch服务器并执行一些基本操作。这个示例使用了官方的elasticsearch-py客户端库。

1. 安装elasticsearch客户端库

首先,你需要安装elasticsearch库。如果你还没有安装,可以使用pip进行安装:

pip install elasticsearch

2. 连接到elasticsearch服务器

以下是一个完整的python脚本,展示了如何连接到elasticsearch服务器,创建索引,添加文档,并进行搜索。

from elasticsearch import elasticsearch, helpers  
# 配置elasticsearch连接  
es = elasticsearch(  
    ['http://localhost:9200'],  # elasticsearch服务器地址和端口  
    http_auth=('username', 'password'),  # 如果需要认证,填写用户名和密码  
    use_ssl=false,  # 如果使用https,设置为true  
    verify_certs=false  # 如果使用https且自签名证书,设置为false  
)  
# 检查连接是否成功  
if es.ping():  
    print("successfully connected to elasticsearch!")  
else:  
    print("could not connect to elasticsearch")  
    exit()  
# 创建索引  
index_name = 'my_index'  
if not es.indices.exists(index=index_name):  
    # 定义索引的映射(schema)  
    mappings = {  
        'properties': {  
            'title': {'type': 'text'},  
            'content': {'type': 'text'},  
            'author': {'type': 'keyword'}  
        }  
    }  
    # 创建索引  
    es.indices.create(index=index_name, body={'mappings': mappings})  
    print(f"index '{index_name}' created successfully.")  
else:  
    print(f"index '{index_name}' already exists.")  
# 添加文档  
documents = [  
    {"_id": 1, "title": "elasticsearch basics", "content": "learn the basics of elasticsearch.", "author": "john doe"},  
    {"_id": 2, "title": "advanced elasticsearch", "content": "go deeper into elasticsearch features.", "author": "jane smith"},  
    {"_id": 3, "title": "elasticsearch performance", "content": "optimize elasticsearch for performance.", "author": "alice johnson"}  
]  
# 使用bulk api批量添加文档  
actions = [  
    {  
        "_index": index_name,  
        "_id": doc['_id'],  
        "_source": doc  
    }  
    for doc in documents  
]  
helpers.bulk(es, actions)  
print("documents added successfully.")  
# 搜索文档  
search_body = {  
    "query": {  
        "match": {  
            "content": "elasticsearch"  
        }  
    }  
}  
response = es.search(index=index_name, body=search_body)  
print("search results:")  
for hit in response['hits']['hits']:  
    print(hit['_source'])  
# 清理(可选):删除索引  
# es.indices.delete(index=index_name)  
# print(f"index '{index_name}' deleted successfully.")

3.代码解释

  • 连接配置:
    • elasticsearch(['http://localhost:9200']):连接到运行在本地主机上的elasticsearch服务器,默认端口为9200。
    • http_auth=('username', 'password'):如果elasticsearch服务器需要认证,填写用户名和密码。
    • use_sslverify_certs:如果连接使用https,可以启用这些选项。
  • 检查连接:
    • 使用es.ping()方法检查连接是否成功。
  • 创建索引:
    • 使用es.indices.exists(index=index_name)检查索引是否存在。
    • 使用es.indices.create(index=index_name, body={'mappings': mappings})创建索引,并定义文档的映射。
  • 添加文档:
    • 使用helpers.bulk(es, actions)批量添加文档到索引中。
  • 搜索文档:
    • 使用es.search(index=index_name, body=search_body)进行搜索,并打印搜索结果。
  • 清理(可选):
    • 使用es.indices.delete(index=index_name)删除索引。

4.注意事项

  • 服务器地址:确保elasticsearch服务器正在运行,并且地址和端口配置正确。
  • 认证:如果elasticsearch服务器需要认证,确保提供正确的用户名和密码。
  • ssl:如果连接使用https,请正确配置use_sslverify_certs选项。

到此这篇关于python es连接服务器的方法的文章就介绍到这了,更多相关python es连接服务器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com