首页 > 编程语言 >Python工具箱系列(三十二)

Python工具箱系列(三十二)

时间:2023-05-15 16:55:58浏览次数:38  
标签:三十二 elastic index Python resp sudo elasticsearch 工具箱 con

Elasticsearch

Elasticsearch是一个基于Lucene的搜索引擎。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful 的API接口。Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是非常流行的企业级搜索引擎。官方支持的客户端语言包括Java、.NET(C#)、PHP、Python、Apache Groovy、Ruby等。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr,而Solr也是基于Lucene开发的。

Elasticsearch的安装方式有许多,官方也特别希望能够在公有云上部署。本文选择最简单的方式,直接在自己掌握的主机(ip:172.29.30.155)上安装。其安装过程如下所述:

# 这个安装过程也有可能非常慢。
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo gpg --dearmor -o /usr/share/keyrings/elasticsearch-keyring.gpg
sudo apt-get install apt-transport-https
echo "deb [signed-by=/usr/share/keyrings/elasticsearch-keyring.gpg] https://artifacts.elastic.co/packages/8.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-8.x.list
sudo apt-get update && sudo apt-get install -y elasticsearch

另一个简单的办法就是直接下载安装包。从官网上下载:

# 在ubuntu bionic目标机的终端下
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-8.3.2-amd64.deb
sudo dpkg -i elasticsearch-8.3.2-amd64.deb

这种方式的好处是可以复制deb文件以多个计算机上,从而节省下载时间。需要安装的目标计算机越多,这种方式越合算。

在ubuntu bionic下,可以使用systemd对其进行管理。相关命令如下:

sudo /bin/systemctl daemon-reload
# 自动启动
sudo /bin/systemctl enable elasticsearch
# 启动
sudo systemctl start elasticsearch
# 查看状态
sudo systemctl status elasticsearch
# 如果出现错误,可以查看日志。
journalctl -f
journalctl -u elasticsearch

# 停止
sudo systemctl stop elasticsearch

# 重置口令,人工指定
/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic -i

# 重置口令,自动生成
/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic

# 测试之
curl --cacert /etc/elasticsearch/certs/http_ca.crt -u elastic https://localhost:9200
curl --cacert /etc/elasticsearch/certs/http_ca.crt -u elastic https://172.29.30.155:9200

获得的响应类似下列信息:

{
  "name" : "dbservers",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "LFs6cpSHTSqLqbx6lRgkvw",
  "version" : {
    "number" : "8.3.2",
    "build_type" : "deb",
    "build_hash" : "8b0b1f23fbebecc3c88e4464319dea8989f374fd",
    "build_date" : "2022-07-06T15:15:15.901688194Z",
    "build_snapshot" : false,
    "lucene_version" : "9.2.0",
    "minimum_wire_compatibility_version" : "7.17.0",
    "minimum_index_compatibility_version" : "7.0.0"
  },
  "tagline" : "You Know, for Search"
}

Elasticsearch的功能非常复杂,需要下功夫学习,本文只从python的角度来使用这个工具。官方推荐的模块安装如下:

pip install elasticsearch

# 为了能够完成安全验证,需要下载相关的证书到本地
scp [email protected]:/etc/elasticsearch/certs/http_ca.crt .

完成后,以下代码简单示例了如何插入记录:

from elasticsearch import Elasticsearch
from datetime import datetime
serverip = "172.29.30.155"
cafile = r"d:\http_ca.crt"
ELASTIC_PASSWORD = "88488848"
indexname = "poetry"
index = 0


def connect():
    client = Elasticsearch(
        f"https://{serverip}:9200", ca_certs=cafile, basic_auth=("elastic", ELASTIC_PASSWORD))
    return client


def docgen(author, content):
    doc = {'author': author, 'text': content, 'timestamp': datetime.now(), }
    return doc


def insert(con, id, doc):
    resp = con.index(index=indexname, id=id, document=doc)
    return resp['result']


def getbyindex(con, id):
    resp = con.get(index=indexname, id=id)
    return resp['_source']


def list(con):
    resp = con.search(index=indexname, query={"match_all": {}})
    print("Got %d Hits:" % resp['hits']['total']['value'])
    for hit in resp['hits']['hits']:
        print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])


def search(con, str):
    resp = con.search(index=indexname, query={"match": {"text": str}})
    print("Got %d Hits:" % resp['hits']['total']['value'])
    for hit in resp['hits']['hits']:
        print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])


# 连接
con = connect()

# 插入记录
index += 1
doc = docgen("李白", "天生我才必有用")
print(insert(con, index, doc))

index += 1
doc = docgen("杜甫", "功盖三分国,名成八阵图,江流石不转,遗恨失吞吴")
print(insert(con, index, doc))

# 准确获得记录
print(getbyindex(con, 1))

# 列出所有记录
list(con)

# 使用搜索功能,找到相关记录
search(con, "天生")

上述代码只是简单地插入了2条记录。真正要发挥作用搜索引擎的能力,必须要将大量的信息导入,同时也要建设集群系统,这部分的内容请阅读官网相关资料,本文不再重复。

标签:三十二,elastic,index,Python,resp,sudo,elasticsearch,工具箱,con
From: https://www.cnblogs.com/shanxihualu/p/17402413.html

相关文章

  • Pycharm的使用和python的部分底层原理
    pycharm的使用1.基本使用1.如何切换主题file(文件)>>>> settings(工具) >>>>  Apperance&behavior(外观和性能)>>>>  Apperance(外观) >>>>  Theme(主题) 2.如何切换不同版本的翻译器file(文件)>>>>  settings(工具) >>>> ......
  • Python实战小案例,值得收藏!
    学Python的时候,很多人都是从理论知识开始学起,但百看不如一练,看再多的理论知识,都不如自己上手实践一下,毕竟实践出真知。本文为大家总结了一些Python实战小案例,建议收藏起来慢慢看。1、已知一个字符串为“hello_world_yoyo”,如何得到一个队列["hello","world","yoyo"]?使......
  • python的垃圾回收
    一、引入python解释器在执行到定义变量的语法时,会申请内存空间来存放变量的值,而内存的容量是有限的,这就涉及到变量值所占用内存空间的回收问题,当一个变量值没有用了(简称垃圾)就应该将其占用的内存给回收掉,那什么样的变量值是没有用的呢?单从逻辑层面分析,我们定义变量将变量值......
  • ChatGPT Plugin开发setup - Java(Spring Boot) Python(fastapi)
    记录一下快速模板,整体很简单,如果不接auth,只需要以下:提供一个/.well-known/ai-plugin.json接口,返回openAI所需要的格式提供openAPI规范的文档CORS设置其他的和普通的web开发类似.本地开发就直接使用localhost即可,前几天官方localhost无法联通,最近应该修复了.要让GPT......
  • Python注释补充之PE8规范
    PE8规范【一】什么是PE8规范PEP是PythonEnhancementProposal的缩写,通常翻译为“Python增强提案”。每个PEP都是一份为Python社区提供的指导Python往更好的方向发展的技术文档,其中的第8号增强提案(PEP8)是针对Python语言编订的代码风格指南。尽管我们可以在保证语法没有......
  • 可用于Python开发的代码编辑器
    市面上适用于Python开发的代码编辑器有很多,我们来简单的说一下一、PyCharm(专业版/社区版)网址:PyCharm:thePythonIDEforProfessionalDevelopersbyJetBrainsPyCharm是一个用于Python开发的集成开发环境(IDE),它提供了丰富的功能和工具,使得Python开发更快、更轻松......
  • python - moviepy音频剪切与拼接
    pip3installmoviepy-ihttps://pypi.tuna.tsinghua.edu.cn/simplefrommoviepy.audio.io.AudioFileClipimportAudioFileClipfrommoviepy.editorimportconcatenate_audioclipsa=AudioFileClip('a.mp3')#读入音频audio1=a.subclip(0,83)#剪切0-83秒......
  • python-flask 技能点使用-03 请求钩子实现审计日志
    场景分析     使用pythonflask开发web系统,该系统是基于用户认证鉴权的web系统,系统中涉及到关键数据的操作,因此需要针对业务操作进行记录(也就是审计日志),便于管理员后期查看,在基于java的Spring系列框架中我们可以借助于AOP面向切面的编程来完成,在使用Flask时可以借助......
  • python的dataframe通过query使用dict字典查询
    示例```params={"坐席姓名":"唐红成"}query_string='and'.join(  [f'({key}=="{val}")'iftype(val)==strelsef'({key}=={val})'forkey,valinparams.items()])df.query(query_string)```......
  • python-flask 技能点使用-01 请求钩子
    场景分析     熟悉java开发的小伙伴应该了解Spring全生命周期以及配套的一系列方法,熟悉Vue开发的小伙伴们应该也熟悉Vue生命周期管理以及一系列方法,使用过Servlet的小伙伴也应该了解其生命周期的概念,本人之前一直从事java开发,现在因为业务需要需要学习python开发,目前......