Elasticsearch integrates springboot

Time:2021-7-30

Official documents

Elasticsearch integrates springboot

Elasticsearch integrates springboot

Elasticsearch integrates springboot

1. Find native dependencies

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

2. Find object

Elasticsearch integrates springboot
3. Analyze the methods in this class

Configure basic items

Elasticsearch integrates springboot
Problem: make sure that the dependencies we import are consistent with those we use

Elasticsearch integrates springboot
Related source code

Elasticsearch integrates springboot

Specific API testing

1. Create index
2. Determine whether the index exists
3. Delete index
4. Create document
5. Crud document

configuration file

@Configuration
public class ElasticSearchClientConfig {

    // spring <beans id="restHighLevelClient" class="RestHighLevelClient">
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200,"http")));
        return client;
    }
}
@SpringBootTest
class HuduEsApiApplicationTests {

    //Object oriented operation
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    //Test index creation request put hudu_ index
    @Test
    void testCreateIndex() throws IOException {
        //1. Create index request
        CreateIndexRequest request = new CreateIndexRequest("hudu_index");
        //2. The client executes the create request
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }

    //The test gets the index and can only judge whether it exists
    @Test
    void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("hudu_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }


    //Test delete index
    @Test
    void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("hudu_index");
        //Delete
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

    //Test add document
    @Test
    void testAddDocument() throws IOException {
        //Create object
        User user = new User("hudu", 3);
        //Create request
        IndexRequest request = new IndexRequest("hudu_index");

        //Rule put / hudu_ index/_ doc/1
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");

        //Put our data into the request
        request.source(JSON.toJSONString(user), XContentType.JSON);

        //The client sends a request to get the response result
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse.toString());//
        System.out.println(indexResponse.status());// Status of the corresponding command line

    }

    //Get the document and judge whether get / index exists/_ doc/1
    @Test
    void testIsExists() throws IOException {
        GetRequest getRequest = new GetRequest("hudu_index", "1");
        //Do not get returned_ Source context
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");

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

    //Get information about the document
    @Test
    void testGetDocument() throws IOException {
        GetRequest getRequest = new GetRequest("hudu_index", "1");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(getResponse.getSourceAsString());// Print the contents of the document
        System.out.println(getResponse);// Everything returned is the same as the command

    }

    //Update document information
    @Test
    void testUpdateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("hudu_index", "1");
        updateRequest.timeout("1s");

        User user = new User("Alex", 20);
        updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);

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

    //Delete文档记录
    @Test
    void testDeleteRequest() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("hudu_index","3");
        deleteRequest.timeout("1s");

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

    //Special and real projects generally insert data in batches!
    @Test
    void testBulkRequest() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        ArrayList<User> userList = new ArrayList<>();
        userList.add(new User("hudu1",20));
        userList.add(new User("hudu2",21));
        userList.add(new User("hudu3",22));
        userList.add(new User("hudu4",23));
        userList.add(new User("hudu5",24));

        //Batch request
        for (int i = 0; i < userList.size(); i++) {
            //For batch update and batch deletion, you can modify the corresponding request here
            bulkRequest.add(
                    new IndexRequest("hudu_index")
                    .id(""+(i+1))
                    .source(JSON.toJSONString(userList.get(i)),XContentType.JSON)
            );

            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println(bulkResponse.hasFailures());// Whether it failed or not. If false is returned, it indicates success
        }

    }

    //Inquiry
    //Searchrequest search request
    //Searchsourcebuilder condition construction
    //Highlightbuilder build highlights
    //Termquerybuilder builds precise queries
    // MatchAllQueryBuilder
    //The xxxquerybuilder corresponds to the command we just saw
    @Test
    void testSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest("hudu_index");
        //Build search criteria
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //Inquiry条件,我们可以使用QueryBuilders 工具类来实现
        //Querybuilders.termquery exact match
        //Querybuilders. Matchallquery() matches all
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "hudu1");
//        MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(sourceBuilder);

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

This work adoptsCC agreement, reprint must indicate the author and the link to this article