ElasticSearch(1)-配置与入门使用
基本概念
https://www.processon.com/view/6167ec86f346fb06a9ed13b7?fromnew=1
docker配置
docker pull elasticsearch:7.12.1
docker run -p 9200:9200 -e discovery.type="single-node" --name elasticsearch elasticsearch:7.12.1
#拷贝分词插件
docker cp D:\\MyData\\Desktop\\elasticsearch-analysis-ik-7.15.1.zip elasticsearch:/usr/share/elasticsearch/plugins
# 分词插件elasticsearch-analysis-ik拷贝到插件路径,解压--注意要下载es对应版本
cd plugin
mkdir ik
unzip elasticsearch-analysis-ik-7.15.1.zip
Es命令行使用
sh-4.4# curl -Xsh-4.4# curl -X GET "localhost:9200/_cat/health?v" 获取es健康状况
epoch timestamp cluster status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1635319461 07:24:21 docker-cluster green 1 1 0 0 0 0 0 0 - 100.0%
sh-4.4# curl -X GET "localhost:9200/_cat/nodes?v" 获取es服务器节点列表
ip heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name
172.17.0.3 45 97 1 0.00 0.08 0.08 cdfhilmrstw * 4cecefb09b76
sh-4.4# curl -X GET "localhost:9200/_cat/indices?v" 获取索引列表
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
sh-4.4# curl -X PUT "localhost:9200/test" 新建test索引
sh-4.4# curl -X GET "localhost:9200/_cat/indices?v"
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
yellow open test ELpWJdz9QEKnqwjmoVmpSg 1 1 0 0 208b 208b
sh-4.4# curl -X DELETE "localhost:9200/test" 删除索引
PostMan使用Es
-
put-增/改(覆盖存储就是修改)
-
delete-删
-
查
查询单条
查询索引下所有文档
localhost:9200/test/_search
搜索引擎分词查询:
搜索某一个字段:content
localhost:9200/test/_search?q=content:运营实习
返回结果:
{
"took": 6,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 2.7103386,
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "1",
"_score": 2.7103386,
"_source": {
"title": "互联网求职",
"content": "寻求运营职位!"
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "2",
"_score": 2.1189923,
"_source": {
"title": "实习生推荐",
"content": "互联网任职,可推荐实习生!"
}
}
]
}
}
搜索多个字段
Spring整合ElasticSeach
引入依赖
- spring-boot-starter-data-elasticsearch
配置Elasticsearch
- cluster-name、cluster-nodes
spring.data.elasticsearch.cluster-name=docker-cluster
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
Spring Data Elasticsearch
- ElasticsearchRepository,他集成了大多数操作,但是某些复杂操作仍需要自己调用ElasticsearchRestTemplate
es配置类,实现ElasticsearchRepository接口即可。
@Repository
//声明好处理哪个实体类(同时会被作为索引名称),主键
public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost, Integer> {
}
- ElasticsearchTemplate已被弃用,使用ElasticsearchRestTemplate
@Autowired
private ElasticsearchRestTemplate elasticTemplate;
-
test
调用上面写的配置类即可。具体的接口包括:save(entity)、saveAll(List)、deleteAll(),这些能够实现简单增删查改了。如:
但是这个类事实上已经不推荐使用了,仅仅推荐用来测试ES,让自己对ES的基础概念和操作有所了解。
之后会介绍RestHighLevelClient
,这是目前项目中实际使用的,官方推荐的接口。