ElasticSearch7.6 SpringbootテストAPIの統合(5)

34949 ワード

一、ES依存の加入
特に、Springbootが持っているES依存がローカルのESバージョンと一致しない可能性がある場合は、ローカルバージョンに変更してください.
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>7.6.1</version>
</dependency>

アリのfast-json依存を加えるには、ES操作のデータはすべてJSON形式であるためです.
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
</dependency>

二、ES配置クラス
/**
 *   ES   ,     bean
 *    :       ;   spring     。
 */
@Configuration //xml - bean
public class ElasticSearchClientConfig {

    //     ES    
    //    spring xml 
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}

三、ESを作成するAPIテスト
まずローカルESを起動してください!
@SpringBootTest
class ElasticsearchApiApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     *         Request     Put test_index
     */
    @Test
    void testCreateIndex() throws IOException {
        // 1.       
        CreateIndexRequest request = new CreateIndexRequest("test_index");
        // 2.          ,IndicesClient,      
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     *        ,        
     */
    @Test
    void testExistIndex() throws IOException {
        // 1.       
        GetIndexRequest request = new GetIndexRequest("test_index");
        // 2.        
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     *        
     */
    @Test
    void testDeleteIndex() throws IOException {
        // 1.       
        DeleteIndexRequest request = new DeleteIndexRequest("test_index");
        // 2.         AcknowledgedResponse         
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

    /**
     *       
     */
    @Test
    void testAddDocument() throws IOException{
        //    
        User user = new User("linsa",3);
        //    
        IndexRequest request = new IndexRequest("test_index");

        //   put /test_index/_doc/1
        request.id("1");
        request.timeout("1s");

        //          ,       json
        request.source(JSON.toJSONString(user), XContentType.JSON);

        //         ,      
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse);
        System.out.println(indexResponse.status());
    }

    /**
     *        
     */
    @Test
    void testGetDocument() throws IOException{
        //       
        GetRequest getRequest = new GetRequest("test_index","1");
        //       
        GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);

        System.out.println(getResponse.getSourceAsString()); //       
        System.out.println(getResponse); //      ,     
    }

    /**
     *        
     */
    @Test
    void testUpdateRequest() throws IOException{
        //    
        UpdateRequest updateRequest = new UpdateRequest("test_index","1");
        updateRequest.timeout("1s");

        //    
        User user = new User("linsa",22);
        //     json    doc 
        updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);

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

    /**
     *       
     */
    @Test
    void testDeleteRequest() throws IOException{
        //    
        DeleteRequest request = new DeleteRequest("test_index","1");
        request.timeout("1s");

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

    /**
     *       
     */
    @Test
    void testBulkRequest() throws IOException{
        //    
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        ArrayList<User> userList = new ArrayList<>();
        userList.add(new User("Tom",12));
        userList.add(new User("Jim",12));
        userList.add(new User("Tom1",12));
        userList.add(new User("Tom2",12));
        userList.add(new User("Tom3",12));
        userList.add(new User("Tom4",12));

        //      
        for (int i=0;i<userList.size();i++){
            //     ,         ,            
            bulkRequest.add(
                    new IndexRequest("test_index").id(""+(i+1)).source(
                            JSON.toJSONString(userList.get(i)),XContentType.JSON
                    )
            );
        }

        //         
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        //    ,  false    
        System.out.println(bulkResponse.hasFailures());
    }

    /**
     *      :
     *  SearchRequest     
     *  SearchSourceBuilder     
     *  HighlightBuilder     
     *  TermQueryBuilder     
     *  MatchAllQueryBuilder       
     *  xxxQueryBuilder
     */
    @Test
    void testSearch() throws IOException{
        //    
        SearchRequest searchRequest = new SearchRequest("test_index");
        //      
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //    
        sourceBuilder.highlighter();
        //    ,    QueryBuilders     
//        QueryBuilders.termQuery()   
//        QueryBuilders.matchAllQuery()     
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name","Tom");
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(sourceBuilder);

        //       
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //       
        System.out.println(JSON.toJSONString(searchResponse.getHits()));
        //        
        for (SearchHit documentFields: searchResponse.getHits().getHits()){
            System.out.println(documentFields.getSourceAsMap());
        }
    }
}