ElasticSearch实战-使用java连接elasticsearch集群并操作

1.需求:

使用java连接elasticsearch集群,并进行相关操作

2.代码:

(1)pom.xml
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
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.1</version>
</dependency>

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.1</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.0</version>
</dependency>

</dependencies>
(2)ES_test.java
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

public class ES_test {

private TransportClient client;

@SuppressWarnings("unchecked")
@Before
public void getClient() throws UnknownHostException {

// 1 设置连接的集群名称
Settings settings = Settings.builder().put("cluster.name", "my-application").build();

// 2 连接集群
client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.1.121"), 9300));

// 3 打印集群名称
//System.out.println(client.toString());
}

@Test
public void createIndex_blog() {
// 创建索引

client.admin().indices().prepareCreate("blog").get();

client.close();
}

@Test
public void deleteIndex() {
// 删除索引
client.admin().indices().prepareDelete("blog").get();

client.close();
}

@Test
public void insertByJson() {
// 使用json常见document

// 1、文档数据准备
String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
+ "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";

// 2 在es中创建文档
IndexResponse indexResponse = client.prepareIndex("blog", "article", "1").setSource(json).execute().actionGet();

// 3 打印返回结果
System.out.println("index: " + indexResponse.getIndex());
System.out.println("type: " + indexResponse.getType());
System.out.println("id: " + indexResponse.getId());
System.out.println("result: " + indexResponse.getResult());

client.close();
}

@Test
public void insertByMap() {
// 使用Map创建document
// 1、文档数据准备
Map<String, Object> json = new HashMap<String, Object>();
json.put("id", "2");
json.put("title", "基于Lucene的搜索服务器");
json.put("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");

// 2 创建文档
IndexResponse indexResponse = client.prepareIndex("blog", "article", "2").setSource(json).execute().actionGet();

// 3 打印返回结果
System.out.println("index: " + indexResponse.getIndex());
System.out.println("type: " + indexResponse.getType());
System.out.println("id: " + indexResponse.getId());
System.out.println("result: " + indexResponse.getResult());

client.close();
}

@Test
public void insertByXContent() throws Throwable {
// 使用XContentBuilder创建document

// 1 通过es自带的帮助类,构建json数据
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", 5)
.field("title", "基于Lucene的搜索服务器").field("content", "sdfs它sdfsdfsdf提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。")
.endObject();

// 2 创建文档
IndexResponse indexResponse = client.prepareIndex("blog", "article", "3").setSource(builder).get();

// 3 打印返回结果
System.out.println("index: " + indexResponse.getIndex());
System.out.println("type: " + indexResponse.getType());
System.out.println("id: " + indexResponse.getId());
System.out.println("result: " + indexResponse.getResult());

client.close();

}

@Test
public void getData() {
// 查询文档
GetResponse response = client.prepareGet("blog", "article", "1").get();

System.out.println(response.getSourceAsString());

client.close();

}

@Test
public void getMultiData() {
// 查询多个文档

MultiGetResponse response = client.prepareMultiGet()
.add("blog", "article", "1")
.add("blog", "article", "2", "3")
.add("blog", "article", "2").get();

//遍历返回结果
for (MultiGetItemResponse multiGetItemResponse : response) {
GetResponse getResponse = multiGetItemResponse.getResponse();

//获取查询结果
if (getResponse.isExists()) {
String sourceAsString = getResponse.getSourceAsString();
System.out.println(sourceAsString);

}
}

client.close();
}
@Test
public void updateData() throws Throwable {

// 1 创建更新数据的请求对象
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("blog");
updateRequest.type("article");
updateRequest.id("3");

updateRequest.doc(XContentFactory.jsonBuilder().startObject()
// 对没有的字段添加, 对已有的字段替换
.field("title", "基于Lucene的搜索服务器")
.field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。大数据前景无限")
.field("createDate", "2017-8-22")
.endObject());

// 2 获取更新后的值
UpdateResponse indexResponse = client.update(updateRequest).get();

// 3 打印返回的结果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("create:" + indexResponse.getResult());// NOOP = NO
// OPeration
// ;
// result=updated
// 表示更新成功

// 4 关闭连接
client.close();
}

@Test
public void testUpsert() throws Exception {

// 设置查询条件, 查找不到则添加
IndexRequest indexRequest = new IndexRequest("blog", "article", "5")
.source(XContentFactory.jsonBuilder().startObject().field("title", "搜索服务器")
.field("content",
"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。")
.endObject());

// 设置更新, 查找到更新下面的设置
UpdateRequest upsert = new UpdateRequest("blog", "article", "5")
.doc(XContentFactory.jsonBuilder().startObject().field("user", "李四").endObject()).upsert(indexRequest);

client.update(upsert).get();
client.close();
}

@Test
public void deleteData() {

// 1 删除文档数据
DeleteResponse indexResponse = client.prepareDelete("blog", "article", "5").get();

// 2 打印返回的结果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("found:" + indexResponse.getResult());

// 3 关闭连接
client.close();
}

@Test
public void matchAllQuery() {

// 查询所有
// 1 执行查询
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.matchAllQuery()).get();

// 2 打印查询结果
SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
System.out.println("查询结果有:" + hits.getTotalHits() + "条");

for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());// 打印出每条结果
}

// 3 关闭连接
client.close();
}

@Test
public void query() {

// 1 条件查询
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.queryStringQuery("大数据")).get();

// 2 打印查询结果
SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
System.out.println("查询结果有:" + hits.getTotalHits() + "条");

for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());// 打印出每条结果
}

// 3 关闭连接
client.close();
}

@Test
public void wildcardQuery() {

// 1 通配符查询
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.wildcardQuery("content", "*全*")).get();

// 2 打印查询结果
SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
System.out.println("查询结果有:" + hits.getTotalHits() + "条");

for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());// 打印出每条结果
}

// 3 关闭连接
client.close();
}

@Test
public void termQuery() {

// 类似于 mysql 中 =

// 1 第一field查询
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.termQuery("content", "全文")).get();

// 2 打印查询结果
SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
System.out.println("查询结果有:" + hits.getTotalHits() + "条");

for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());// 打印出每条结果
}

// 3 关闭连接
client.close();
}

@Test
public void fuzzy() {

// 1 模糊查询
SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.fuzzyQuery("title", "lucene")).get();

// 2 打印查询结果
SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
System.out.println("查询结果有:" + hits.getTotalHits() + "条");

Iterator<SearchHit> iterator = hits.iterator();

while (iterator.hasNext()) {
SearchHit searchHit = iterator.next(); // 每个查询对象

System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印
}

// 3 关闭连接
client.close();
}

@Test
public void createMapping() throws Exception {

// 1设置mapping
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject("article")
.startObject("properties")
.startObject("id1")
.field("type", "text")
.field("store", "true").endObject()
.startObject("title2")
.field("type", "text").field("store", "false").endObject()
.startObject("content")
.field("type", "text").field("store", "true").endObject()
.endObject().endObject().endObject();

// 2 添加mapping
PutMappingRequest mapping = Requests.putMappingRequest("blog4").type("article").source(builder);

client.admin().indices().putMapping(mapping).get();

// 3 关闭资源
client.close();
}

// 创建使用ik分词器的mapping
@Test
public void createMapping_ik() throws Exception {

// 1设置mapping
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject("article")
.startObject("properties")
.startObject("id1")
.field("type", "text").field("store", "true")
.field("analyzer", "ik_smart")
.endObject()
.startObject("title2").field("type", "text")
.field("store", "false").field("analyzer", "ik_smart").
endObject().startObject("content")
.field("type", "text").field("store", "true")
.field("analyzer", "ik_smart").endObject().endObject()
.endObject().endObject();

// 2 添加mapping
PutMappingRequest mapping = Requests.putMappingRequest("blog4").type("article").source(builder);
client.admin().indices().putMapping(mapping).get();

// 3 关闭资源
client.close();
}

// 创建文档,以map形式
@Test
public void createDocumentByMap_forik() {

HashMap<String, String> map = new HashMap<String, String>();
map.put("id1", "2");
map.put("title2", "Lucene");
map.put("content", "它提供了一个分布式的web接口");

IndexResponse response = client.prepareIndex("blog4", "article", "3").setSource(map).execute().actionGet();

// 打印返回的结果
System.out.println("结果:" + response.getResult());
System.out.println("id:" + response.getId());
System.out.println("index:" + response.getIndex());
System.out.println("type:" + response.getType());
System.out.println("版本:" + response.getVersion());

// 关闭资源
client.close();
}

// 词条查询
@Test
public void queryTerm_forik() {

// 分析结果:因为是默认被standard analyzer分词器分词,大写字母全部转为了小写字母,并存入了倒排索引以供搜索。term是确切查询, 必须要匹配到大写的Name。
SearchResponse response = client.prepareSearch("blog4")
.setTypes("article")
.setQuery(QueryBuilders.termQuery("content", "web"))
.get();

// 获取查询命中结果
SearchHits hits = response.getHits();

System.out.println("结果条数:" + hits.getTotalHits());

for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}

}


3.结果:

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2021 Movle
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信