SpringBoot集成ES-7.8

原生依赖

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.8.1</version>
</dependency>

初始化对象

RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));
client.close();

然后分析这个对象中的方法即可(api)

创建项目

这里以https://start.spring.io/的方式进行创建

🐤环境规定

  • SpringBoot:2.2.5.RELEASE
  • JDK:1.8

🐸修改elasticsearch.version

<properties>
	<elasticsearch.version>7.8.1</elasticsearch.version>
</properties>

🐬创建配置类ElasticSearchClientConfig.java

@Configuration
public class ElasticSearchClientConfig {

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

}

索引API

创建索引

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testCreateIndex() throws IOException {
        // 1.创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("bntang666_index");

        // 2.客户端执行请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);

        System.out.println(response);
    }

}

判断索引是否存在

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testExistsIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("bntang666_index");

        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);

        System.out.println(exists);
    }

}

删除索引

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("test2");

        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);

        System.out.println(response.isAcknowledged());
    }
}

文档API

创建POJO(实体类)

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private String name;
    private int age;
}

添加文档

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testAddDocument() throws IOException {
        // 1.创建对象
        User user = new User("灰灰", 23);

        // 2.创建请求
        IndexRequest request = new IndexRequest("bntang666_index");

        // 3.规则
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));

        // 4.将我们的数据放入请求中
        request.source(JSON.toJSONString(user), XContentType.JSON);

        // 5.客户端发送请求,获取响应结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
        System.out.println(response.status());
    }

}

判断文档是否存在

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testIsExists() throws IOException {
        GetRequest request = new GetRequest("bntang666_index","1");

        // 不获取返回的_source的上下文了
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");

        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

}

获取文档信息

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testGetDocument() throws IOException {
        GetRequest request = new GetRequest("bntang666_index", "1");

        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSource());
        System.out.println(response);
    }

}

修改文档信息

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testUpdateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("bntang666_index", "1");
        request.timeout("1s");

        User user = new User("灰灰说Java", 18);

        request.doc(JSON.toJSONString(user), XContentType.JSON);

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

}

删除文档信息

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("bntang666_index", "1");
        request.timeout("1s");

        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

}

批量插入文档信息

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testBatchInsertDocument() throws IOException {
        BulkRequest request = new BulkRequest();
        request.timeout("10s");

        List<Object> list = new ArrayList<>();
        list.add(new User("BNTang1", 23));
        list.add(new User("BNTang2", 23));
        list.add(new User("BNTang3", 23));

        list.add(new User("BNTang6661", 23));
        list.add(new User("BNTang6662", 23));
        list.add(new User("BNTang6663", 23));

        for (int i = 0; i < list.size(); i++) {
            request.add(
                    new IndexRequest("bntang666_index")
                    .id("" + (i + 1))
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON)
            );
        }

        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.hasFailures());
    }

}

🐤批量修改和批量删除只需要在循环当中修改对应的API即可

查询API

精确查询

@SpringBootTest
class SpringbootEsApiApplicationTests {

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

    @Test
    void testSearch() throws IOException {
        SearchRequest request = new SearchRequest("bntang666_index");

        // 构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 查询条件,我们可以使用
        TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "BNTang1");
        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(response.getHits()));
        System.out.println("======================================");

        for (SearchHit searchHit : response.getHits().getHits()) {
            System.out.println(searchHit.getSourceAsMap());
        }
    }

}
  • SearchRequest:搜索请求
  • SearchSourceBuilder:条件构造
  • HighlightBuilder:构建高亮
  • TermQueryBuilder:精确查询
  • MatchAllQueryBuilder:匹配所有

xxx QueryBuild 对应的就是Kibana中的命令

posted @ 2020-08-17 20:11  BNTang  阅读(882)  评论(0编辑  收藏  举报