用python脚本更新Elasticsearch数据库

本文介绍了如何使用Python通过ElasticsearchAPI从一个本地文本文件中读取callid,然后根据callid更新Elasticsearch索引中相关文档的languagename字段。原始代码和针对新版本的优化版本都包含在内,展示了向_doc类型文档的批量更新过程。
摘要由CSDN通过智能技术生成

这段代码的主要功能是通过Elasticsearch与一个索引(index)进行交互,读取本地文本文件中的callid,并根据callid更新索引中相关文档的字段值。以下是详细解释: 

# -*- coding: utf-8 -*-
# @Time    : 2023/3/29 11:27
# @Author  : hjcui
# @Site    : 
# @File    : Update_ES.py
# @Software: PyCharm

# 原始的
from elasticsearch import Elasticsearch
import os

es_conn = Elasticsearch(['194.169.55.12:9200'])
index = 'cr-all-2023.03'
type = 'doc'
suffix = '505_'
src_file = r'./wewr_callid_0328.txt'

with open(src_file,'r',encoding='utf-8') as sf:
    for callid in sf:
        guid = suffix + callid.strip()
        es_query = \
            {
                "query": {
                    "term": {
                        "callid.keyword": {
                            "value": callid.strip()
                        }
                    }
                }
            }
        docs = es_conn.search(index=index,body=es_query)
        source = docs['hits']['hits'][0]['_source']
        # 如果要修改的字段值与数据库中的不一致时,显示'successful': 1,否则是'successful': 0
        result = es_conn.update(index=index,doc_type='doc',id=guid,body={'doc':{'languagename':"other"}})
        print(result)



# 针对新版本优化的
# -*- coding: utf-8 -*-
from elasticsearch import Elasticsearch, helpers
import os

es_conn = Elasticsearch(['194.169.55.12:9200'])
index = 'index-2023.03'
doc_type = '_doc'  # 自Elasticsearch 7.x版本起,推荐使用_doc作为默认类型
suffix = '505_'
src_file = r'./wewr_callid_0328.txt'

def update_docs(callids):
    actions = []
    for callid in callids:
        guid = suffix + callid.strip()
        es_query = {
            "_id": guid,
            "_index": index,
            "doc": {"languagename": "other"},
            "doc_as_upsert": True  # 如果文档不存在,则创建新文档(upsert)
        }
        actions.append({"update": es_query})

    if actions:
        # 批量执行更新操作
        result = helpers.bulk(es_conn, actions)
        print(f"成功更新/插入了{result[0]}个文档,失败了{result[1]}个。")

with open(src_file, 'r', encoding='utf-8') as sf:
    callids = [line.strip() for line in sf]
    
    # 对读取到的callids列表进行更新操作
    update_docs(callids)

  • 14
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python可以与Elasticsearch进行交互,通过ElasticsearchPython客户端API,您可以轻松地使用PythonElasticsearch中检索和索引数据。 以下是使用Python Elasticsearch客户端API的基本步骤: 1.安装Python Elasticsearch客户端API 在终端或命令提示符下,运行以下命令安装Python Elasticsearch客户端API: ``` pip install elasticsearch ``` 2.建立与Elasticsearch的连接 在Python脚本中,您可以使用以下代码创建到Elasticsearch的连接: ``` from elasticsearch import Elasticsearch es = Elasticsearch([{'host': 'localhost', 'port': 9200}]) ``` 其中,`host`和`port`参数指定Elasticsearch集群的主机和端口号。如果您的Elasticsearch集群有多个节点,可以指定多个主机和端口号,以逗号分隔。 3.创建索引 在Elasticsearch中,索引是一个包含一组相关文档的逻辑命名空间。您可以使用以下代码在Elasticsearch中创建索引: ``` es.indices.create(index='my_index') ``` 4.添加文档 要将文档添加到Elasticsearch中,请使用以下代码: ``` doc = {'title': 'My document', 'content': 'This is my first document.'} es.index(index='my_index', doc_type='my_type', body=doc) ``` 其中,`index`参数指定要将文档添加到的索引,`doc_type`参数指定文档类型,`body`参数指定文档内容。 5.搜索文档 要从Elasticsearch中搜索文档,请使用以下代码: ``` query = {'query': {'match': {'title': 'document'}}} res = es.search(index='my_index', body=query) ``` 其中,`query`参数指定要执行的查询,`res`变量包含搜索结果。 这是使用Python Elasticsearch客户端API的基本步骤。您可以使用其他API方法进行更高级的操作,例如更新文档、删除文档和聚合查询。请参阅Elasticsearch Python客户端API文档以获取更多信息。 ### 回答2: Elasticsearch是一个开源的分布式搜索和分析引擎,建立在Apache Lucene之上。它使用JSON格式进行数据的存储和索引,通过RESTful API进行数据的检索和查询。Elasticsearch的核心概念包括索引、类型、文档和字段。 在Python中使用Elasticsearch可以通过安装`elasticsearch`库来实现。首先,我们需要连接到Elasticsearch集群,可以使用`Elasticsearch`类进行连接。例如: ```python from elasticsearch import Elasticsearch es = Elasticsearch([{"host": "localhost", "port": 9200}]) ``` 连接成功后,我们可以创建索引并添加文档。索引类似于数据库中的表,用于存储和管理文档。例如,我们创建一个名为`my-index`的索引,并在其中添加一个文档: ```python es.indices.create(index="my-index") document = { "title": "Python Elasticsearch", "content": "Elasticsearch is a powerful search engine." } es.index(index="my-index", doc_type="_doc", body=document) ``` 接下来,我们可以执行各种查询操作。例如,通过`search`方法可以执行全文搜索: ```python query = { "query": { "match": { "content": "search engine" } } } results = es.search(index="my-index", doc_type="_doc", body=query) for hit in results["hits"]["hits"]: print(hit["_source"]) ``` 此外,还可以使用`get`方法根据ID获取单个文档,使用`delete`方法删除文档,使用`update`方法更新文档等等。 总之,Python中的Elasticsearch库提供了简单易用的API来与Elasticsearch进行交互。通过它,我们能够方便地创建索引、添加、查询和更新文档,实现全文搜索和数据分析等功能。 ### 回答3: Elasticsearch是一个开源的分布式搜索和分析引擎,它基于Lucene库开发而成。Python提供了Elasticsearch的官方客户端库,使得在Python中使用Elasticsearch变得非常方便。 使用Python中的elasticsearch库,我们可以创建一个Elasticsearch连接实例,并指定要连接的集群。我们可以使用连接实例来执行各种操作,如索引数据、搜索数据、删除数据等。 在使用Elasticsearch之前,首先要安装Elasticsearch并启动它的服务。然后,我们需要在Python中安装elasticsearch库,我们可以使用pip这个包管理器来安装它。安装完成后,在我们的Python脚本中引入elasticsearch库。 首先,我们需要创建一个连接实例。通过指定主机和端口,我们可以连接到Elasticsearch集群。我们还可以设置其他的参数,如认证信息、连接超时等。 然后,我们可以使用连接实例来进行各种操作。例如,我们可以使用索引方法来创建一个新的索引。我们可以指定索引的名称、类型和文档的数据。要更新或删除文档,我们可以使用相关的方法。 与索引相关的操作还包括搜索和聚合。我们可以使用搜索方法对索引中的数据进行全文搜索,还可以使用聚合方法对数据进行分析和统计。 另外,我们还可以使用Elasticsearch提供的一些高级功能,如建立索引别名、设置分片和副本、执行批量操作等。 总之,Python中的elasticsearch库提供了一个便捷的方式来与Elasticsearch进行交互,我们可以通过这个库来索引、搜索和分析我们的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值