elasticsearch7.6.2 - springboot調用


一 整合

整合代碼放在 https://gitee.com/elvinle/jd_pachong.git 中, 並不復雜 

elasticsearch 官方推薦使用 rest 方式進行操作.

 

二 庫操作

private static String INDEX_DEFAULT = "elvin";

private static String INDEX_JD = "jd_goods";

@Autowired
RestHighLevelClient client;

//region 索引庫操作
//創建索引
@Test
public void createIndex() throws Exception {
    CreateIndexRequest createReq = new CreateIndexRequest(INDEX_DEFAULT);
    CreateIndexResponse resp = client.indices().create(createReq, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(resp));
}

//判斷索引是否存在
@Test
public void existsIndex() throws Exception {
    GetIndexRequest createIndexReq = new GetIndexRequest(INDEX_DEFAULT);
    boolean exists = client.indices().exists(createIndexReq, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(exists));
}

//刪除索引
@Test
public void deleteIndex() throws Exception {
    DeleteIndexRequest deleteReq = new DeleteIndexRequest(INDEX_DEFAULT);
    AcknowledgedResponse resp = client.indices().delete(deleteReq, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(resp));
}
//endregion

建庫一般都是提前建好的.

 

三 文檔操作

//region 文檔操作
//創建文檔
@Test
public void addDoc() throws Exception{
    User user = User.builder()
            .id("1")
            .name("elvin")
            .age(29)
            .work("java軟件開發工程師")
            .hobby(new ArrayList<String>() {{
                add("籃球");
                add("羽毛球");
                add("乒乓球");
                add("游泳");
            }})
            .desc("一個喜歡運動, 愛老婆的boy").build();
    IndexRequest req = new IndexRequest(INDEX_DEFAULT);
    req.id(user.getId());
    req.timeout("5s");
    req.source(JSON.toJSONString(user), XContentType.JSON);
    IndexResponse resp = client.index(req, RequestOptions.DEFAULT);
    System.out.println("添加文檔 -> " + req.toString());
    System.out.println("結果 -> " + resp.toString());
    System.out.println("狀態 -> " + resp.status());
}

//判斷文檔是否存在
@Test
public void existsDoc() throws Exception{
    GetRequest req = new GetRequest(INDEX_DEFAULT, "1");
    boolean exists = client.exists(req, RequestOptions.DEFAULT);
    System.out.println("文檔是否存在 : " + exists);
}

//根據id獲取文檔
@Test
public void getDoc() throws Exception{
    GetRequest req = new GetRequest(INDEX_DEFAULT, "1");
    GetResponse resp = client.get(req, RequestOptions.DEFAULT);
    System.out.println("獲取到的文檔 : " + resp.getSourceAsString());
}

//修改文檔
@Test
public void updateDoc() throws Exception{
    User user = new User();
    user.setDesc("熱愛生活和熱愛工作");

    UpdateRequest req = new UpdateRequest(INDEX_DEFAULT, "1");
    req.id("1");
    req.timeout("5s");
    req.doc(JSON.toJSONString(user), XContentType.JSON);

    UpdateResponse resp = client.update(req, RequestOptions.DEFAULT);
    System.out.println("修改文檔 --> " + req.toString());
    System.out.println("修改結果 --> " + resp.status());

    //getDoc();
}

//根據id刪除文檔
@Test
public void deleteDoc() throws Exception{
    DeleteRequest req = new DeleteRequest(INDEX_DEFAULT, "1");
    DeleteResponse resp = client.delete(req, RequestOptions.DEFAULT);
    System.out.println("獲取到的文檔 : " + resp.status());
}

//批量添加
@Test
public void bulkAddDoc() throws Exception{
    List<User> userList = new ArrayList<>();
    for (int i = 1; i < 11; i++) {
        User user = User.builder()
                .id(String.valueOf(i))
                .name("elvin" + i)
                .age(29)
                .work("java軟件開發工程師")
                .hobby(new ArrayList<String>() {{
                    add("籃球");
                    add("羽毛球");
                    add("乒乓球");
                    add("游泳");
                }})
                .desc("一個喜歡運動, 愛老婆的boy")
                .build();
        userList.add(user);
    }

    BulkRequest req = new BulkRequest();
    req.timeout("5s");
    for (int i = 0; i < userList.size(); i++) {
        req.add(new IndexRequest(INDEX_DEFAULT)
                .id(String.valueOf(i + 1 ))
                .source(JSON.toJSONString(userList.get(i)), XContentType.JSON)
        );
    }
    BulkResponse resp = client.bulk(req, RequestOptions.DEFAULT);
    System.out.println("批量添加文檔 -> " + resp.hasFailures());
}

//查詢文檔
@Test
public void searchDoc() throws Exception{
    SearchRequest req = new SearchRequest(INDEX_JD);

    //構建查詢條件
    SearchSourceBuilder  reqSourceBuilder = new SearchSourceBuilder();
    //設置分頁
    reqSourceBuilder.from(0);
    reqSourceBuilder.size(5);
    //設置高亮
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.field("title");
    highlightBuilder.preTags("<span style='color:red'>");
    highlightBuilder.postTags("</span>");
    reqSourceBuilder.highlighter(highlightBuilder);
    //term查詢
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "java");
    reqSourceBuilder.query(termQueryBuilder);
    reqSourceBuilder.timeout(new TimeValue(5, TimeUnit.SECONDS));

    req.source(reqSourceBuilder);

    SearchResponse resp = client.search(req, RequestOptions.DEFAULT);
    System.out.println("測試查詢文檔-----"+JSON.toJSONString(resp.getHits()));
    System.out.println("=====================");
    for (SearchHit documentFields : resp.getHits().getHits()) {
        System.out.println("測試查詢文檔--遍歷參數--"+documentFields.getSourceAsMap());
    }

    System.out.println("----------替換高亮列-----------");
    //解析結果
    ArrayList<Map<String, Object>> list = new ArrayList<>();
    for (SearchHit hit : resp.getHits().getHits()) {
        //解析高亮的字段
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        HighlightField title = highlightFields.get("title");
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        //解析高亮的字段
        if(title != null){
            Text[] fragments = title.fragments();
            String n_title = "";
            for (Text text : fragments) {
                n_title += text;
            }
            //將高亮的字段替換掉原來的字段
            sourceAsMap.put("title", n_title);
        }
        list.add(sourceAsMap);
    }
    list.forEach(n-> System.out.println(JSON.toJSONString(n)));
}
//endregion

文檔操作中, 可能查詢比較多用一點. 增刪改可以通過 canal 來完成.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM