ElasticSearch 整合 SpringBoot

HuDu發表於2020-11-13

官方文件

ElasticSearch 整合 SpringBoot

ElasticSearch 整合 SpringBoot

ElasticSearch 整合 SpringBoot

1、找到原生的依賴

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

2、找物件

ElasticSearch 整合 SpringBoot
3、分析這個類中的方法

配置基本的專案

ElasticSearch 整合 SpringBoot
問題:一定要保證我們匯入的依賴和我們使用的一致

ElasticSearch 整合 SpringBoot
相關原始碼

ElasticSearch 整合 SpringBoot

具體的API測試

1、建立索引
2、判斷索引是否存在
3、刪除索引
4、建立文件
5、CRUD文件

配置檔案

@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 {

    //物件導向來操作
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    // 測試索引的建立 Request請求 PUT hudu_index
    @Test
    void testCreateIndex() throws IOException {
        //1、建立索引請求
        CreateIndexRequest request = new CreateIndexRequest("hudu_index");
        //2、客戶端執行建立請求
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }

    //測試獲取索引,只能判斷其是否存在
    @Test
    void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("hudu_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }


    //測試刪除索引
    @Test
    void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("hudu_index");
        //刪除
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

    //測試新增文件
    @Test
    void testAddDocument() throws IOException {
        //建立物件
        User user = new User("hudu", 3);
        //建立請求
        IndexRequest request = new IndexRequest("hudu_index");

        //規則 PUT /hudu_index/_doc/1
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");

        //將我們的資料放入請求
        request.source(JSON.toJSONString(user), XContentType.JSON);

        //客戶端傳送請求,獲取響應結果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse.toString());//
        System.out.println(indexResponse.status());//對應命令列的狀態

    }

    //獲取文件,判斷是否存在 get /index/_doc/1
    @Test
    void testIsExists() throws IOException {
        GetRequest getRequest = new GetRequest("hudu_index", "1");
        //不獲取返回的_source 的上下文
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");

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

    //獲得文件的資訊
    @Test
    void testGetDocument() throws IOException {
        GetRequest getRequest = new GetRequest("hudu_index", "1");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(getResponse.getSourceAsString());//列印文件的內容
        System.out.println(getResponse);//返回的全部內容和命令是一樣的

    }

    //更新文件資訊
    @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());
    }

    //刪除文件記錄
    @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());
    }

    //特殊的,真實的專案一般都會批量插入資料!
    @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));

        //批處理請求
        for (int i = 0; i < userList.size(); i++) {
            //批量更新和批量刪除,就在這裡修改對應的請求即可
            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());//是否失敗,返回false表示成功
        }

    }

    //查詢
    //SearchRequest搜尋請求
    //SearchSourceBuilder 條件構造
    //HighlightBuilder 構建高亮
    //termQueryBuilder 構建精確查詢
    // MatchAllQueryBuilder
    // xxxQueryBuilder 對應我們剛才看到的命令
    @Test
    void testSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest("hudu_index");
        //構建搜尋條件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //查詢條件,我們可以使用QueryBuilders 工具類來實現
        //QueryBuilders.termQuery 精確匹配
        //QueryBuilders.matchAllQuery() 匹配所有
        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());
        }
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章