Python工具箱系列(三十二)

2025-12-13 0 228

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 root@172.29.30.155:/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条记录。真正要发挥作用搜索引擎的能力,必须要将大量的信息导入,同时也要建设集群系统,这部分的内容请阅读官网相关资料,本文不再重复。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

申明:本文由第三方发布,内容仅代表作者观点,与本网站无关。对本文以及其中全部或者部分内容的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。本网发布或转载文章出于传递更多信息之目的,并不意味着赞同其观点或证实其描述,也不代表本网对其真实性负责。

左子网 编程相关 Python工具箱系列(三十二) https://www.zuozi.net/36276.html

常见问题
  • 1、自动:拍下后,点击(下载)链接即可下载;2、手动:拍下后,联系卖家发放即可或者联系官方找开发者发货。
查看详情
  • 1、源码默认交易周期:手动发货商品为1-3天,并且用户付款金额将会进入平台担保直到交易完成或者3-7天即可发放,如遇纠纷无限期延长收款金额直至纠纷解决或者退款!;
查看详情
  • 1、描述:源码描述(含标题)与实际源码不一致的(例:货不对板); 2、演示:有演示站时,与实际源码小于95%一致的(但描述中有”不保证完全一样、有变化的可能性”类似显著声明的除外); 3、发货:不发货可无理由退款; 4、安装:免费提供安装服务的源码但卖家不履行的; 5、收费:价格虚标,额外收取其他费用的(但描述中有显著声明或双方交易前有商定的除外); 6、其他:如质量方面的硬性常规问题BUG等。 注:经核实符合上述任一,均支持退款,但卖家予以积极解决问题则除外。
查看详情
  • 1、左子会对双方交易的过程及交易商品的快照进行永久存档,以确保交易的真实、有效、安全! 2、左子无法对如“永久包更新”、“永久技术支持”等类似交易之后的商家承诺做担保,请买家自行鉴别; 3、在源码同时有网站演示与图片演示,且站演与图演不一致时,默认按图演作为纠纷评判依据(特别声明或有商定除外); 4、在没有”无任何正当退款依据”的前提下,商品写有”一旦售出,概不支持退款”等类似的声明,视为无效声明; 5、在未拍下前,双方在QQ上所商定的交易内容,亦可成为纠纷评判依据(商定与描述冲突时,商定为准); 6、因聊天记录可作为纠纷评判依据,故双方联系时,只与对方在左子上所留的QQ、手机号沟通,以防对方不承认自我承诺。 7、虽然交易产生纠纷的几率很小,但一定要保留如聊天记录、手机短信等这样的重要信息,以防产生纠纷时便于左子介入快速处理。
查看详情

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务