ElasticSearch:8.X
依赖
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.6.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.json</artifactId>
<version>2.0.1</version>
</dependency>
配置
@Bean
public ElasticsearchClient elasticsearchClient() {
RestClient restClient = RestClient.builder(new HttpHost(host, port)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
增删改查
@Resource
private ElasticsearchClient client;
@Resource
private ITbHotelService hotelService;
private final String id = "441836";
=====批量新增文档=====
@Test
public void batchAddDocument() throws IOException {
BulkRequest.Builder bulk = new BulkRequest.Builder();
List<Demo> list = demoService.list();
list.forEach(h -> {
bulk.operations(op ->
op.index(idx -> idx
.index("DemoIndex")
.id(String.valueOf(demo.getId()))
.document(demo)));
});
BulkResponse result = client.bulk(bulk.build());
System.out.println(result);
}
=====单个新增文档=====
@Test
public void addDocument() throws IOException {
Demo demo = demoService.getById(id);
client.index(i -> i.index("DemoIndex").id(id).document(demo));
}
=====获取单个文档=====
@Test
public void getDocument() throws IOException {
GetResponse<Demo> demo = client.get(g -> g.index("DemoIndex").id(id), Demo.class);
System.out.println(demo.found() ? demo.source() : null);
}
=====删除单个文档=====
@Test
public void deleteDocument() throws IOException {
client.delete(d -> d.index("DemoIndex").id(id));
}
=====查找文档=====
@Test
public void searchDocument() throws IOException {
SearchResponse<Demo> search = client.search(s -> s
.index("DemoIndex")
.query(q -> q
.fuzzy(f -> f
.field("all")
.value("7天")
.fuzziness("2")))
.from(0)
.size(100)
.sort(t -> t.field(o -> o.field("score").order(SortOrder.Desc)))
, TbHotelEs.class);
System.out.println(search);
}
ElasticSearch:7.X