SpringBoot集成ElasticSearch使用

目录

    • 1. 客户端依赖
    • 2. 配置
    • 3. API
        • 3.1 索引
            • 3.1.1 创建索引
            • 3.1.2 判断索引是否存在
            • 3.1.3 删除索引
        • 3.2 文档
            • 3.2.1 创建文档
            • 3.2.2 判断文档是否存在
            • 3.2.3 获取文档内容
            • 3.2.4 更新文档
            • 3.2.5 删除文档
            • 3.2.6 批量插入
            • 3.2.7 搜索

注:这里的客户端使用的是RestClient,没有使用spring-boot-starter-data-elasticsearch

1. 客户端依赖

<elasticsearch.version>7.6.2elasticsearch.version>

<dependency>
    <groupId>org.elasticsearch.clientgroupId>
    <artifactId>elasticsearch-rest-high-level-clientartifactId>
    <version>${elasticsearch.version}version>
dependency>

2. 配置

@Configuration
public class Config {

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

3. API

3.1 索引

3.1.1 创建索引
@SpringBootTest(classes = {EsDemo1Application.class})
@RunWith(SpringRunner.class)
public class EsDemo1ApplicationTests {

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

    @Test
    public void test1() {
        System.out.println(client);
    }

    /**
     * 创建索引
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("springboot_index_test");
        client.indices().create(request, RequestOptions.DEFAULT);
    }

	@After
    public void after() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
3.1.2 判断索引是否存在
    /**
     * 判断索引是否存在
     */
    @Test
    public void test4() throws IOException {
        GetIndexRequest request = new GetIndexRequest("springboot_index_test");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
3.1.3 删除索引
    /**
     * 删除索引
     */
    @Test
    public void test3() throws IOException {
        DeleteIndexRequest delete = new DeleteIndexRequest("springboot_index_test");
        AcknowledgedResponse response = client.indices().delete(delete, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

3.2 文档

3.2.1 创建文档
    /**
     * 创建文档
     */
    @Test
    public void test5() throws IOException {
        Student student = new Student("李四", 22);
        IndexRequest request = new IndexRequest("springboot_index_test");
        request.id(2 + "");
        request.source(JSONObject.toJSONString(student), XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
        System.out.println(response.status());
    }
3.2.2 判断文档是否存在
    /**
     * 判断文档是否存在
     *
     * @throws IOException
     */
    @Test
    public void test6() throws IOException {
//        GetRequest request = new GetRequest("springboot_index_test");
//        request.id("2");
        GetRequest request = new GetRequest("springboot_index_test", "1");
        // 不获取上下文 _source
        request.fetchSourceContext(new FetchSourceContext(false));
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
3.2.3 获取文档内容
    /**
     * 获取文档内容
     */
    @Test
    public void test7() throws IOException {
        GetRequest request = new GetRequest("springboot_index_test", 1 + "");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
        System.out.println(response.toString());
    }
3.2.4 更新文档
    /**
     * 更新文档
     *
     * @throws IOException
     */
    @Test
    public void test8() throws IOException {
        UpdateRequest request = new UpdateRequest("springboot_index_test", 1 + "");
        GetRequest get = new GetRequest("springboot_index_test", 1 + "");
        GetResponse response = client.get(get, RequestOptions.DEFAULT);
        Student student = JSONObject.parseObject(response.getSourceAsString(), Student.class);
        student.setAge(101);
        request.doc(JSONObject.toJSONString(student), XContentType.JSON);
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        System.out.println(updateResponse.status());
    }
3.2.5 删除文档
    /**
     * 删除文档
     *
     * @throws IOException
     */
    @Test
    public void test9() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("springboot_index_test", 2 + "");
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
    }
3.2.6 批量插入
    /**
     * 批量插入
     */
    @Test
    public void test10() throws IOException {
        Student student1 = new Student("test1", 1);
        Student student2 = new Student("test2", 2);
        Student student3 = new Student("test3", 3);
        Student student4 = new Student("test4", 4);
        Student student5 = new Student("test5", 5);
        ArrayList<Student> studentList = new ArrayList<>();
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);
        studentList.add(student4);
        studentList.add(student5);
        BulkRequest bulkRequest = new BulkRequest("springboot_index_test");
        for (int i = 0; i < studentList.size(); i++) {
            bulkRequest.add(new IndexRequest()
                    .id(i + "")
                    .source(JSONObject.toJSONString(studentList.get(i)), XContentType.JSON)
            );
        }
        // 超时时间
        bulkRequest.timeout(new TimeValue(10, TimeUnit.SECONDS));
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.status());
    }
3.2.7 搜索
    /**
     * 查询
     */
    @Test
    public void search() throws IOException {
        SearchRequest searchRequest = new SearchRequest("springboot_index_test");

        // 构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 排序
        searchSourceBuilder.sort("age", SortOrder.DESC);
        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        searchSourceBuilder.highlighter(highlightBuilder);

        // 查询构造器 查询条件
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "test1");
        searchSourceBuilder.query(matchQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        for (SearchHit searchHit :
                hits) {
            System.out.println(searchHit.getSourceAsMap());
        }
    }

你可能感兴趣的:(elasticsearch)