ElasticSearch7.x简单使用

ElasticSearch7.6.x

什么是ElasticSearch?

Elasticsearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。

ES的基本概念

对比于现有的关系型数据库去学习

Relational DBElasticsearch
数据库(database)索引(indices)
表(tables)类型(types)
行(rows)文档(document)
字段(columns)字段(fields)

Restful风格:

methodurl地址描述
PUTlocalhost:9200/indices/
types/document_ID
创建文档(指定ID)
POSTlocalhost:9200/indices/
types
创建文档(随机ID)
POSTlocalhost:9200/indices/
types/document_ID/_update
修改文档
DELETElocalhost:9200/indices/
types/document_ID
删除文档
GETlocalhost:9200/indices/
types/document_ID
通过ID查询文档
POSTlocalhost:9200/indices/
types/_search
查询所有的文档

indices:n. 指数;目录(index的复数)

基础测试:

1
2
PUT /test01/_doc/2
{ }

请求头+请求体

关于索引的操作

创建索引

1
2
3
4
PUT /indices/types/document_ID
{

}

数据类型:

FieldType
字符串类型text 、 keyword
数值类型long, integer, short, byte, double,
float,half_float, scaled_float
日期类型date
布尔值类型boolean
二进制类型binary

指定字段的类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
PUT /test01
{
"mappings": {
"properties": {
"name":{
"type": "text"
},
"age":{
"type": "integer"
},
"birthday":{
"type": "date"
}
}
}
}

可以通过 GET 请求获取具体的信息!

1
GET indices

get _cat/ 可以获得es的当前的很多信息

1
GET _cat/indices?v

更新数据

  • put
1
2
3
4
put /indices/types/document_ID
{
"name":"summer"
}
  • POST _update
1
2
3
4
5
6
POST /indices/types/document_ID/_update
{
"doc":{
"name":"summer"
}
}

put 的方法只是简单的覆盖而已,后面加_update只会修改修改的数据。

删除索引

1
2
3
DELETE /indices
DELETE /indices/_doc/
DELETE /indices/_doc/document_ID

关于文档的基本操作

基本操作:

添加数据

1
2
3
4
5
6
7
PUT /summer/user/1
{
"name":"summer",
"age":"22",
"desc":"学java很开心",
"tags":["帅哥","暖男","666"]
}

修改内容

  • put
1
2
3
4
put /indices/types/document_ID
{
"name":"summer"
}
  • POST _update
1
2
3
4
5
6
POST /indices/types/document_ID/_update
{
"doc":{
"name":"summer"
}
}

简单地搜索!

1
GET /summer/user/_search?q=name:summer

条件:

1
q=name:summer

复杂操作搜索

查找

1
2
3
4
5
6
7
8
GET /summer/user/_search
{
"query": {
"match": {
"name": "summer"
}
}
}

查出来的结果:

Snipaste_2020-04-15_15-46-25

我们发现我们的结果在hits中,想要的信息在hits中的hits

n. 击打;网页点击数;采样数(hit的复数)

限制只显示哪个字段

select name,age from user ;

1
2
3
4
5
6
7
8
9
GET /summer/user/_search
{
"query": {
"match": {
"desc":"学java很开心"
}
},
"_source": ["name","age"]
}

排序

select * from user ORDER BY age;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
GET /summer/user/_search
{
"query": {
"match": {
"desc":"学java很开心"
}
},
"sort": [
{
"age": {
"order": "desc"
}
}
]
}

分页 from size

select * from user limit from ,size ;

1
2
3
4
5
6
7
8
9
10
11
GET /summer/user/_search
{
"query": {
"match": {
"desc":"学java很开心"
}
},
"_source": ["name","age"],
"from": 0,
"size": 2
}

布尔值查询

bool 就是SQL语句中的where

must:

select * from user where name = ‘summer’ and desc = ‘学java很开心’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
GET /summer/user/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"name":"summer"
}
},
{
"match": {
"desc":"学java很开心"
}
}
]
}
}
}

should:

select * from user where name = ‘summer’ or desc = ‘学java很开心’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
GET /summer/user/_search
{
"query": {
"bool": {
"should": [
{
"match": {
"name":"summer"
}
},
{
"match": {
"desc":"学java很开心"
}
}
]
}
}
}

must_not

select * from user where not name = ‘summer’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
GET /summer/user/_search
{
"query": {
"bool": {
"must_not": [
{
"match": {
"name":"summer"
}
}
]
}
}
}

过滤器 filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
GET /summer/user/_search
{
"query": {
"bool": {
"must": [
{
"name":"summer"
}
]
, "filter": {
"range": {
"age": {
"gte": 10,
"lte": 20
}
}
}
}
}

匹配多个条件

1
2
3
4
5
6
7
8
GET /summer/user/_search
{
"query": {
"match": {
"tags": "暖男 高中生"
}
}
}

精确查询

关于分词:
term :直接查询精确的
match:会使用分词器解析!(先分析文档,然后在通过分析的文档进行查询!)

1
2
3
4
5
6
7
8
GET /summer/user/_search
{
"query": {
"term": {
"name":"summer"
}
}
}

高亮查询

1
2
3
4
5
6
7
8
9
10
11
12
13
GET /summer/user/_search
{
"query": {
"match": {
"name":"summer"
}
}
, "highlight": {
"fields": {
"name":{}
}
}
}

Snipaste_2020-04-15_17-01-43

集成springboot

原生依赖导入

1
2
3
4
5
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>

注:如果在创建springboot时直接选择了elasticsearch,就需要去springboot中去修改版本,因为springboot中默认的是6.X

1
2
3
4
5
<properties>
<java.version>1.8</java.version>
<!--自定义版本-->
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>

自定义一下版本。

将elasticsearch核心类配置进入springboot中

1
2
3
4
5
6
7
8
9
@Configuration
public class ElasticSearchConfig {

@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.01",9200,"http")));
}

}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package com.summer;
@SpringBootTest
class SpringbootEsApiApplicationTests {

@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;

@Test
void contextLoads() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("summer_002");
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response);
}

// 测试获取索引,判断其是否存在
@Test
void TestExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("summer_001");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}

// 测试删除索引
@Test
void TestDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("summer_001");
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete);
}


// 测试添加文档
@Test
void TestAddDocument() throws IOException {
//创建对象
User user = new User("summer",20);
//创建请求
IndexRequest request = new IndexRequest("summer_002");
//规则 /summer_02/_doc/1
request.id("1");
request.timeout("1s");
// 将数据放入请求中
request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求
IndexResponse index = client.index(request, RequestOptions.DEFAULT);
//查看结果
System.out.println(index.toString());
System.out.println(index.status());
}


// 获得文档的信息
@Test
void testGetDocument() throws IOException {
//创建get请求
GetRequest getRequest = new GetRequest("summer_002","1");
//执行命令 客户端发送,获得结果
GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
//打印结果
System.out.println(documentFields);
System.out.println(documentFields.getSourceAsString());
}


// 更新文档的信息
@Test
void testUpdateDocument() throws IOException {
//创建请求
UpdateRequest updateRequest = new UpdateRequest("summer_002","1");
User user = new User("pppnut",22);
UpdateRequest doc = updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse update = client.update(doc, RequestOptions.DEFAULT);
System.out.println(update);
System.out.println(update.status());
}

// 删除文档记录
@Test
void testDeleteDocument() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("summer_002","1");
DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete);
System.out.println(delete.status());
}


// 特殊的,真的项目一般都会批量插入数据!
@Test
void testBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
ArrayList<User> users = new ArrayList<>();
for (int i = 10; i < 22; i++) {
users.add(new User("summer"+i,i));
}
for (int i = 0; i < users.size(); i++) {
bulkRequest.add(
new IndexRequest("summer_002")
.source(JSON.toJSONString(users.get(i)),XContentType.JSON));
}
bulkRequest.timeout("10S");
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk);
System.out.println(bulk.status());
}

// 查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 构建高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxx QueryBuilder 对应我们刚才看到的命令!
@Test
void SearchRequest() throws IOException {
SearchRequest searchRequest = new SearchRequest("summer_002");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "summer");
// MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
SearchSourceBuilder query = sourceBuilder.query(termQueryBuilder);
SearchRequest source = searchRequest.source(query);
SearchResponse searchResponse = client.search(source, RequestOptions.DEFAULT);
System.out.println(searchResponse);
System.out.println(JSON.toJSONString(searchResponse.getHits()));
System.out.println(searchResponse.getHits());
}
}

总结java对ElasticSearch进行操作

  1. 请求头
  2. 请求体
  3. 请求体的具体操作
  4. 执行请求体

报错:发现索引必须都是小写

1
2
[summer_001Spring] ElasticsearchStatusException[Elasticsearch exception [type=invalid_index_name_exception, reason=Invalid index name [summer_001Spring], must be lowercase]
]

坑点: 这里必须要new IndexRequest,不然值会重复

1
2
3
4
5
6
7
8
users.forEach(System.out::println);
System.out.println("====================================================================");
for (int i = 0; i < users.size(); i++) {
bulkRequest.add(
new IndexRequest("summer_002")
.source(JSON.toJSONString(users.get(i)),XContentType.JSON));
System.out.println(users.get(i));
}
-------------本文结束 感谢您的阅读-------------
文章对我有益,我要小额赞赏...