Elasticsearch7.6.2 – springboot call

Time:2021-9-24

I. integration

Integrate code on   https://gitee.com/elvinle/jd_ In pachong.git, it is not complicated

Elastic search officially recommends using rest mode for operation

 

Second library operation

private static String INDEX_DEFAULT = "elvin";

private static String INDEX_JD = "jd_goods";

@Autowired
RestHighLevelClient client;

//Region index library operation
//Create index
@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));
}

//Determine whether the index exists
@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));
}

//Delete index
@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

The construction of the library is generally completed in advance

 

III. document operation

//Region document operation
//Create document
@Test
public void addDoc() throws Exception{
    User user = User.builder()
            .id("1")
            .name("elvin")
            .age(29)
            . work ("Java Software Development Engineer")
            .hobby(new ArrayList() {{
                Add ("Basketball");
                Add ("badminton");
                Add ("table tennis");
                Add ("swimming");
            }})
            . desc ("a boy who likes sports and loves his wife"). 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 ("add document - >" + req. Tostring());
    System. Out. Println ("result - >" + resp. Tostring());
    System. Out. Println ("status - >" + resp. Status());
}

//Determine whether the document exists
@Test
public void existsDoc() throws Exception{
    GetRequest req = new GetRequest(INDEX_DEFAULT, "1");
    boolean exists = client.exists(req, RequestOptions.DEFAULT);
    System. Out. Println ("does the document exist:" + exists);
}

//Get document by ID
@Test
public void getDoc() throws Exception{
    GetRequest req = new GetRequest(INDEX_DEFAULT, "1");
    GetResponse resp = client.get(req, RequestOptions.DEFAULT);
    System. Out. Println ("obtained document:" + resp. Getsourceasstring());
}

//Modify document
@Test
public void updateDoc() throws Exception{
    User user = new User();
    User.setdesc ("love life and work");

    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 ("modify document -- >" + req. Tostring());
    System. Out. Println ("modification result -- >" + resp. Status());

    //getDoc();
}

//Delete document by ID
@Test
public void deleteDoc() throws Exception{
    DeleteRequest req = new DeleteRequest(INDEX_DEFAULT, "1");
    DeleteResponse resp = client.delete(req, RequestOptions.DEFAULT);
    System. Out. Println ("obtained document:" + resp. Status());
}

//Batch add
@Test
public void bulkAddDoc() throws Exception{
    List 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 Software Development Engineer")
                .hobby(new ArrayList() {{
                    Add ("Basketball");
                    Add ("badminton");
                    Add ("table tennis");
                    Add ("swimming");
                }})
                . desc ("a boy who likes sports and loves his wife")
                .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 ("batch add documents - >" + resp. Hasfailures());
}

//Query document
@Test
public void searchDoc() throws Exception{
    SearchRequest req = new SearchRequest(INDEX_JD);

    //Build query criteria
    SearchSourceBuilder  reqSourceBuilder = new SearchSourceBuilder();
    //Set paging
    reqSourceBuilder.from(0);
    reqSourceBuilder.size(5);
    //Set highlight
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.field("title");
    highlightBuilder.preTags("");
    highlightBuilder.postTags("");
    reqSourceBuilder.highlighter(highlightBuilder);
    //Term query
    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 ("test query document -----" + json.tojsonstring (resp. Gethits());
    System.out.println("=====================");
    for (SearchHit documentFields : resp.getHits().getHits()) {
        System. Out. Println ("test query document -- traversal parameters --" + documentfields. Getsourceasmap());
    }

    System. Out. Println ("---------- replace highlighted column -----------");
    //Analytical results
    ArrayList> list = new ArrayList<>();
    for (SearchHit hit : resp.getHits().getHits()) {
        //Resolve highlighted fields
        Map highlightFields = hit.getHighlightFields();
        HighlightField title = highlightFields.get("title");
        Map sourceAsMap = hit.getSourceAsMap();
        //Resolve highlighted fields
        if(title != null){
            Text[] fragments = title.fragments();
            String n_title = "";
            for (Text text : fragments) {
                n_title += text;
            }
            //Replace the highlighted field with the original field
            sourceAsMap.put("title", n_title);
        }
        list.add(sourceAsMap);
    }
    list.forEach(n-> System.out.println(JSON.toJSONString(n)));
}
//endregion

In document operation, you may use more queries. You can add, delete and modify through   Canal to finish