首页 > 编程语言 >python ES连接服务器的方法P9

python ES连接服务器的方法P9

时间:2024-10-25 13:47:50浏览次数:1  
标签:index name python P9 索引 Elasticsearch es 服务器 ES

连接Elasticsearch(ES)服务器是进行数据搜索和分析的常用操作。Elasticsearch是一个基于Lucene的搜索引擎,提供了RESTful API来进行索引、搜索和管理数据。

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

1. 安装Elasticsearch客户端库

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

bash复制代码

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.代码解释

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

4.注意事项

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

本博客参考悠兔机场。转载请注明出处!

标签:index,name,python,P9,索引,Elasticsearch,es,服务器,ES
From: https://www.cnblogs.com/westworldss/p/18502361

相关文章

  • MySQL和PostgreSQL数据库有哪些关键差异_1
    在数据库管理系统的选择中,MySQL和PostgreSQL是两个极具代表性的选项。这两个数据库系统在多个关键方面的差异包括:1.性能和优化;2.可扩展性和复杂数据处理;3.安全性和可靠性;4.社区和企业支持;5.特定场景的适用性。MySQL以其轻量级和易于使用的特性在小型到中型应用中广受欢迎,而Postgr......
  • 在Java中如何使用Spring Boot快速开发RESTful服务
    Java中通过SpringBoot快速开发RESTful服务关键步骤包含:1、利用SpringInitializr生成项目框架、2、创建资源表示类(ResourceRepresentationClass)、3、制作资源控制器(ResourceController)、4、编写业务逻辑层(ServiceLayer)、5、集成数据访问层(RepositoryLayer)、6、配置数据库连......
  • PostgreSQL基础(一)
    简介PostgreSQL是一个免费的对象-关系数据库服务器(ORDBMS),在灵活的BSD许可证下发行。PostgreSQL的Slogan是“世界上最先进的开源关系型数据库”号称是“开源界的Oracle”,去O首选PostgreSQL官网https://www.postgresql.org/PostgreSQL中文社区http://www.postqres.cn/v2/......
  • IDEA 微服务,配置services菜单管理服务启动和调试
    打开工程下的workspace配置RunDashboard<componentname="RunDashboard"><optionname="configurationTypes"><set><optionvalue="SpringBootApplicationConfigurationType"/></set>......
  • 关于ubuntu系统升级遇到的问题:upgrades to the development release are only.......
    主要问题在于使用的是命令:sudodo-release-upgrade-d这将会寻找最新的版本进行安装,但是如果最新版本不稳定的话请求会受到拒绝,导致更新无法进行。具体区别如下:do-release-upgrade是Ubuntu系统用于升级到新版本的命令。当你运行这个命令时,系统会检查是否有新版本可用,并且会自......
  • 在K8S中,pod中readness 和 liveness 的区别和各自应用场景是什么?
    在Kubernetes(K8s)中,Pod的readiness和liveness探针是两种重要的健康检查机制,它们各自有着不同的应用场景和功能。以下是对这两者的详细解释:LivenessProbe(存活探针):作用:Liveness探针主要用于探测应用是否还活着。如果检测到应用没有存活(即探针失败),Kubernetes会杀掉当前Pod并重......
  • 【CodeForces训练记录VP】Codeforces Round 933 (Div. 3)
    https://codeforces.com/contest/1941训练情况50min后罚坐反思C题刚开始思路错了,以为是删字符串最后面,然后漏考虑掉两字符串部分拼接的情况A题直接模拟,求\(a_i+b_j\lek\)的对数。#include<bits/stdc++.h>#defineintlonglongusingnamespacestd;voidsolve......
  • <Project-11 Calculator> 计算器 0.5 液体、长度、温度单位 转换器 liquid_measures HTM
    前言这是一个综合性的单位换算工具,提供了多种常用计量单位之间的转换功能。不断完善style各页面风格统一,格式一致。容量单位换算支持在公制单位(升、毫升、立方厘米)美制容量单位(加仑、夸脱、品脱、杯、液体盎司)厨房计量单位(汤匙、茶匙、米杯)之间相互转换长度单位换算公......
  • 中间人攻击(https降级攻击)和iptables命令分析
    中间人攻击以下是一个简单的中间人攻击示例,结合ARP欺骗和流量修改:1.进行ARP欺骗首先,使用 arpspoof 进行ARP欺骗,将受害者的流量重定向到攻击者的机器上:sudoarpspoof-ieth0-t172.29.144.50172.29.144.12.启用IP转发确保IP转发已启用,以便攻击者可以将......
  • CAN201 In Class Test 1 Thursday Session
    CAN201InClassTest1ThursdaySession2MultiplayerNumberGuessingGame(UDPSockets)ObjectiveThisinclasstestisrequiredtousePythonforsocketprogramming.Youwillcreateamultiplayer“numberguessing”gameusingUDPsocketsprogramming,wi......