赞
踩
目录
随着数据量的不断增加,传统的查询检索在速度上遇到了瓶颈,这个时候就需要一个更具性能的技术来支持大数据量的查询检索,本文就介绍下Elasticsearch。
Elasticsearch(ES)是一个基于Apache Lucene构建的开源搜索引擎,它提供了强大的搜索、分析和聚合功能,具有快速、可扩展和易于使用的特点。为了更好地理解ES,以下是一些关键概念:
对于新手来说,有限关注索引、文档的概念即可,以及就是写入、查询。
索引(Index):
类型(Type)(在Elasticsearch 7.0之后已废弃):
文档(Document):
字段(Field):
映射(Mapping):
节点(Node):
集群(Cluster):
分片(Shard):
副本(Replica):
查询DSL(Domain Specific Language):
这些概念构成了Elasticsearch的核心架构和操作方式。了解这些概念对于有效地使用Elasticsearch至关重要。
from elasticsearch7 import Elasticsearch, helpers
- # 1. 创建Elasticsearch连接
- es = Elasticsearch(
- hosts=["http://127.0.0.1:9200"], # 服务地址与端口
- http_auth=("user", "password"), # 用户名,密码
- )
- # 2. 定义索引名称
- index_name = "test_index_01"
-
- # 3. 如果索引已存在,删除它(仅供演示,实际应用时不需要这步)
- if es.indices.exists(index=index_name):
- es.indices.delete(index=index_name)
-
- # 4. 创建索引
- es.indices.create(index=index_name)
- # 构建测试数据
- docs=[]
- docs.append("He is a good boy")
- docs.append("I like to eat apple")
- docs.append("She is a good girl")
- docs.append("My name is John")
- docs.append("My team is the best")
-
- # 5. 灌库指令
- # to_keywords 进行了分词处理,以便全文检索
- actions = [
- {"_index": index_name, "_source": {"keywords": to_keywords(doc), "text": doc}}
- for doc in docs
- ]
-
- # 6. 文本灌库
- helpers.bulk(es, actions)

- # ES 的查询语言
- # keywords 是写入数据时候定义的字段,本例也可以按text原始内容查询
- search_query = {"match": {"keywords": to_keywords(query_string)}}
- res = es.search(index=index_name, query=search_query, size=top_n)
- # 取出查询到的记录
- return [hit["_source"]["text"] for hit in res["hits"]["hits"]]
Elasticsearch通常与两个其他开源项目一起被提及,这三个项目合称为“Elastic Stack”,也被称为“ELK Stack”。三剑客这个名称听起来更霸气。这三个项目分别是:
Elasticsearch:
Logstash:
Kibana:
这三个工具共同工作,提供了一个强大的解决方案,用于数据收集、存储、搜索、分析和可视化。由于Elasticsearch、Logstash和Kibana的首字母分别是E、L和K,因此它们通常被称为“ELK Stack”。不过,随着Elastic Stack的发展,现在还包括了其他工具,如Beats(轻量级数据传输工具),因此有时也被称为“Elastic Stack”。
这个工具专门介绍下,他可以方便的查看ES的index、具体index的数据、以及查询。这个工具主要是很轻量化,属于edge、Chrome浏览器的一个插件,这里我以edge为例说明使用。
edge浏览器右上角…——扩展——打开Microsoft Edge加载项——左上角搜索框输入“elasticsearch head”,右侧就可以搜索出这个插件
点击安装即可。
下次使用的时候,点击浏览器扩展,再点击es-client即可打开主界面
然后就是具体使用了,自己操作下就会了,很简单的。
以上就是今天要讲的内容,本文主要介绍了ES的初步使用,包括基本概念、代码连接数据库、创建索引、写数据、查数据等,最后介绍了一些相关的工具。
当然,实践才是更好的学习途径。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。