Reference: www.elastic.co/guide/en/el…

1. Elasticsearch dependency

1.1 the Maven rely on

  • Elasticsearch-rest-high-level -client specifies an advanced REST client object
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
  </dependency>
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.74</version>
  </dependency>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.18</version>
  </dependency>

  <! -- Es service dependencies -->
  <dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.8.0</version>
  </dependency>
  <! -- Es client dependencies -->
  <dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.8.0</version>
  </dependency>
</dependencies>
Copy the code

1.2 Public Methods

  • Json beautification tool class
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class EsUser {
    private String name;
    private Integer age;
    private String sex;

    public String toJsonString(a) {
        return JSONObject.toJSONString(this); }}Copy the code

Test Elasticsearch

2.1 Service Connection

  • RestHighLevelClient: advanced client
import java.io.IOException;
import java.util.Objects;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.After;
import org.junit.Before;

public class ElasticsearchTest {
    /** * Connect to the client */
    private RestHighLevelClient client;

    @Before
    public void init(a) {
        HttpHost serverHost = new HttpHost("127.0.0.1".9200);
        client = new RestHighLevelClient(RestClient.builder(serverHost));
    }

    @After
    public void destroy(a) {
        if (Objects.nonNull(client)) {
            try {
                client.close();
            } catch(IOException e) { e.printStackTrace(); }}}}Copy the code

2.2 Index Operations

import com.codecoord.elasticsearch.utils.PrintUtil;
import java.io.IOException;
import java.util.Objects;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class ElasticsearchIndexTest {
    /** * Connect to the client */
    private RestHighLevelClient client;

    @Before
    public void init(a) {
        HttpHost serverHost = new HttpHost("127.0.0.1".9200);
        client = new RestHighLevelClient(RestClient.builder(serverHost));
    }

    @After
    public void destroy(a) {
        if (Objects.nonNull(client)) {
            try {
                client.close();
            } catch(IOException e) { e.printStackTrace(); }}}/** * create index; /** * create index
    @Test
    public void testCreate(a) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("java");
        CreateIndexResponse response = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        PrintUtil.buttyPrint(response);
    }

    /** * Query index information */
    @Test
    public void testQuery(a) throws IOException {
        GetIndexRequest request = new GetIndexRequest("java");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        // Get the alias
        PrintUtil.buttyPrint(response.getAliases(), "getAliases");
        // Get the default Settings
        PrintUtil.buttyPrint(response.getDefaultSettings(), "getDefaultSettings");
        // Get the index information
        PrintUtil.buttyPrint(response.getIndices(), "getIndices");
        // Get the mapping information
        PrintUtil.buttyPrint(response.getMappings(), "getMappings");
    }

    /** * Delete index */
    @Test
    public void testDelete(a) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("java"); AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT); PrintUtil.buttyPrint(response); }}Copy the code

2.3 Document Operations

  • The following document operation is an example operation, and you only need to change the query for advanced queries
import com.codecoord.elasticsearch.domain.EsUser;
import com.codecoord.elasticsearch.utils.PrintUtil;
import java.io.IOException;
import java.util.Objects;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class ElasticsearchDocTest {
    /** * Connect to the client */
    private RestHighLevelClient client;

    @Before
    public void init() {
        HttpHost serverHost = new HttpHost("127.0.0.1", 9200); client = new RestHighLevelClient(RestClient.builder(serverHost)); } @After public void destroy() { if (Objects.nonNull(client)) { try { client.close(); } catch (IOException e) { e.printStackTrace(); }}}/** * Create document */
    @Test
    public void testCreate() throws IOException {
        IndexRequest request = new IndexRequest();
        // Specify the index
        request.index("java");
        / / specified id
        request.id("1001");
        // Store data
        EsUser user = new EsUser("zhangsan", 30, "Male");
        // Specify the source content
        request.source(user.toJsonString(), XContentType.JSON);
        / / request
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        PrintUtil.buttyPrint(response);
    }

    /** * Modify the document */
    @Test
    public void testUpdate() throws IOException {
        UpdateRequest request = new UpdateRequest();
        // Specify the index
        request.index("java");
        / / specified id
        request.id("1001");

        // Update the content
        EsUser user = new EsUser("ES", 18."Female");
        request.doc(user.toJsonString(), XContentType.JSON);

        / / ES request
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        PrintUtil.buttyPrint(response);
    }

    /**
     * 文档查询
     */
    @Test
    public void testQuery() throws IOException {
        GetRequest request = new GetRequest().index("java").id("1001");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        PrintUtil.buttyPrint(response.getSource());
    }

    /** * Delete document */
    @Test
    public void testDelete() throws IOException {
        DeleteRequest request = new DeleteRequest().index("java").id("1001");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        PrintUtil.buttyPrint(response);
    }

    /** * Batch operation, for adding, deleting and modifying */
    @Test
    public void testBatch() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        / / delete first
        bulkRequest.add(new DeleteRequest().index("java").id("1001"));
        / / add
        EsUser user = new EsUser("EsJava", 18."Male");
        bulkRequest.add(new IndexRequest().index("java").id("1002").source(user.toJsonString(), XContentType.JSON));

        BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        PrintUtil.buttyPrint(responses);
    }

    /** * match query */
    @Test
    public void testAdvanceMatchQuery() throws IOException {
        SearchRequest request = new SearchRequest("java");

        // Construct the query condition
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // Match the query
        /// QueryBuilders provides query matching relationships in commands
        /// Query all
        /// QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        /// Single query
        /// QueryBuilder queryBuilder = QueryBuilders.matchQuery("age", 18);
        /// The phrase matches the query
        QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("name"."EsJava");
        builder.query(queryBuilder);

        request.source(builder);
        SearchResponse responses = client.search(request, RequestOptions.DEFAULT);
        PrintUtil.buttyPrint(responses.getHits());
    }

    /** * bool Query */
    @Test
    public void testAdvanceBoolQuery() throws IOException {
        SearchRequest request = new SearchRequest("java");

        // Construct the query condition
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        // must
        queryBuilder.must(QueryBuilders.matchQuery("age", 18));
        // mustNot
        queryBuilder.mustNot(QueryBuilders.matchQuery("sex"."Female"));
        // should
        queryBuilder.should(QueryBuilders.matchQuery("name"."zhangsan"));

        builder.query(queryBuilder);
        request.source(builder);
        SearchResponse responses = client.search(request, RequestOptions.DEFAULT);
        PrintUtil.buttyPrint(responses.getHits());
    }

    /** * Paging query */
    @Test
    public void testAdvancePageQuery() throws IOException {
        SearchRequest request = new SearchRequest("java");

        // Query the query condition
        SearchSourceBuilder builder = new SearchSourceBuilder();
        MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();

        // query <==> select
        builder.query(queryBuilder);

        // Paging query
        builder.from(0);
        builder.size(2);

        // Specify sort
        builder.sort("age", SortOrder.ASC); request.source(builder); SearchResponse responses = client.search(request, RequestOptions.DEFAULT); for (SearchHit searchHit : responses.getHits()) { System.out.println(searchHit.getSourceAsString()); }}/** * Highlight query */
    @Test
    public void testAdvanceHighLightQuery() throws IOException {
        SearchRequest request = new SearchRequest("java");

        // Query the query condition
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // Note that highlighting all queries does not make sense
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name"."java");
        builder.query(queryBuilder);

        // Highlight search, which is the same as query
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name"); builder.highlighter(highlightBuilder); request.source(builder); SearchResponse responses = client.search(request, RequestOptions.DEFAULT); for (SearchHit searchHit : responses.getHits()) { System.out.println(searchHit.getHighlightFields()); }}}Copy the code