SpringBoot集成ElasticSearch

100 阅读1分钟

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>

配置

// es没有配置安全校验
@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();
    //使用mybatis查询出对象集合
    List<Demo> list = demoService.list();
    list.forEach(h -> {
        bulk.operations(op ->
                op.index(idx -> idx
                        //demoIndex为es索引
                        .index("DemoIndex")
                        //创建es文档的id
                        .id(String.valueOf(demo.getId()))
                        //传入对象
                        .document(demo)));
    });
    //统一执行新增es文档操作
    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