The learning springboot project of elasticsearch version 6.6. X integrates the advanced client elasticsearch rest high level client

Keywords: Java ElasticSearch RESTful

Official website learning address

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.6/java-rest-high.html


Construction project

Create a spring boot maven project
Import dependency

     <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.6.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.6.2</version>
        </dependency>

First test code

    @Test
    public void contextLoads() throws IOException {
//        Create a connection to es
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                        //,new HttpHost("localhost", 9200, "http")
                        ));
//     Create a request
        GetRequest getRequest = new GetRequest(
                "test5",
                "doc",
                "1");

//        Determine whether a document exists
        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);

        System.out.println(exists);
        client.close();

    }

Query SearchRequest

Introductory case


    @Test
    public void contextLoads() throws IOException {
//        Create a connection to es
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                        //,new HttpHost("localhost", 9200, "http")
                        ));




//        query


//        Create a query request object
        SearchRequest searchRequest = new SearchRequest();

//        Object to create query criteria
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // Query all data
        // searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //  Query by criteria
        searchSourceBuilder.query(QueryBuilders.termQuery("name","hong"));

//        Put the query object into the request object
        searchRequest.source(searchSourceBuilder);
//     Set requested index
        searchRequest.indices("test3");
//        Set the type of request
        searchRequest.types("_doc");
//        Set query type
        searchRequest.searchType(SearchType.QUERY_THEN_FETCH);

//        Make a query
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        //      Get the returned data and print it
        SearchHits hits = search.getHits();
        //        Number of data obtained
        System.out.println(hits.getTotalHits());

        client.close();

    }
}

Methods in QueryBuilders

First, store a piece of data i like eating and kuing. The default word breaker should divide the content into "i" "like" "eating" "and" "kuing"

must,mustNot,should

must(QueryBuilders) :   AND
mustNot(QueryBuilders): NOT
should:                  : OR
@Test
    public void testQueryBuilder2() {
        QueryBuilder queryBuilder = QueryBuilders.boolQuery()
            .must(QueryBuilders.termQuery("user", "kimchy"))
            .mustNot(QueryBuilders.termQuery("message", "nihao"))
            .should(QueryBuilders.termQuery("gender", "male"));
        searchFunction(queryBuilder);
    }

matchQuery

QueryBuilders.matchQuery("supplierName",param)
The search term will be segmented and matched with the target query field. If any word in the segmentation matches the target field, it can be queried.
param = "i" Can be found i
param = "i li" Can be found
param = "i like" Can be found
param = "i like eat" Can be found
param = "and" Can be found
param = "kuing" Can be found

Paging from size

Query all the qualified data before paging

  searchSourceBuilder
  .query(QueryBuilders.matchAllQuery())
  .from(0).size(2);

matchAllQuery

Find everything in the index

  searchSourceBuilder.query(QueryBuilders.matchAllQuery())

sort

sort

After the data is queried, it can be paged and sorted

   searchSourceBuilder
                 .query(QueryBuilders.matchAllQuery())
                 .from(0)
                 .size(3)
         .sort("age", SortOrder.ASC);

filter

filter

   searchSourceBuilder
                 .query(QueryBuilders.matchAllQuery())
                 .from(0)
                 .size(3)
         .sort("age", SortOrder.ASC)
         .postFilter(QueryBuilders.rangeQuery("age").from(30).to(31));

explain

The query of installation matching degree is the score of each data. The higher the score, the more you can query

    searchSourceBuilder
                 .query(QueryBuilders.matchAllQuery())
                 .from(0)
                 .size(3)
         .sort("age", SortOrder.ASC)
         .postFilter(QueryBuilders.rangeQuery("age").from(30).to(31))

.explain(true);

multiMatchQuery

multiMatchQuery(“text”, “field1”, “field2”…); Match multiple fields with wildcard lines

We don't know which field the value to query is in, so we need to match multiple fields. As long as one field meets the conditions, it can be matched

  searchSourceBuilder
                 .query(QueryBuilders.multiMatchQuery("jing","name","age"))
                 .from(0)
                 .size(3)
         .sort("age", SortOrder.ASC)
         .postFilter(QueryBuilders.rangeQuery("age").from(30).to(31))
         .explain(true);

queryStringQuery

Fuzzy query is performed for each field according to the value + represents must contain - represents cannot contain

    //The query document must contain changge, and the document without hejiu (each field will be queried) + means must contain - means cannot contain
    QueryBuilder builder = QueryBuilders.queryStringQuery("+changge  -hejiu");

Fuzzy query can be performed by specific fields

         searchSourceBuilder
         .query(QueryBuilders.queryStringQuery("name:tome*"))

CommonTersQuery

Specify fields for fuzzy query

 QueryBuilder builder = 
 QueryBuilders.commonTermsQuery("name","jing");

simpleQueryStringQuery

Note: fuzzy query is performed for each field according to the value. As long as one matches, the article will be returned

   //As long as all fields contain changge or hejiui, they are returned
    QueryBuilder builder = 
    QueryBuilders.simpleQueryStringQuery("jing");

termQuery

Accurate matching

The value of the field must be this before it can be queried

searchSourceBuilder.query(QueryBuilders.termQuery("name","hong"));

polymerization

In ES, all aggregation instances are constructed by static methods provided by the AggregationBuilders class,

(1)Count the number of a field
  ValueCountBuilder vcb=  AggregationBuilders.count("count_uid").field("uid");
(2)De duplication counts the number of a field (with a small error)
 CardinalityBuilder cb= AggregationBuilders.cardinality("distinct_count_uid").field("uid");
(3)Aggregation filtration
FilterAggregationBuilder fab= AggregationBuilders.filter("uid_filter").filter(QueryBuilders.queryStringQuery("uid:001"));
(4)Group by a field
TermsBuilder tb=  AggregationBuilders.terms("group_name").field("name");
(5)Sum
SumBuilder  sumBuilder=	AggregationBuilders.sum("sum_price").field("price");
(6)Average
AvgBuilder ab= AggregationBuilders.avg("avg_price").field("price");
(7)Find the maximum value
MaxBuilder mb= AggregationBuilders.max("max_price").field("price"); 
(8)Find the minimum value
MinBuilder min=	AggregationBuilders.min("min_price").field("price");
(9)Group by date interval
DateHistogramBuilder dhb= AggregationBuilders.dateHistogram("dh").field("date");
(10)Get the results in the aggregation
TopHitsBuilder thb=  AggregationBuilders.topHits("top_result");
(11)Nested aggregation
NestedBuilder nb= AggregationBuilders.nested("negsted_path").path("quests");
(12)Reverse nesting
AggregationBuilders.reverseNested("res_negsted").path("kps ");

aggregation

There is a method aggregation () in the searchSourceBuilder object
Parameters are aggregate function objects

Number after grouping

First query the data according to the query criteria, and then aggregate the query



//        Object to create query criteria
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        TermsAggregationBuilder aggration = AggregationBuilders.terms("by_age").field("age");
        searchSourceBuilder
//                 .query(QueryBuilders.multiMatchQuery("jing","name","age"))
                .query(QueryBuilders.matchAllQuery())
                .aggregation(aggration);

After aggregating groups, get the number of groups

//        Make a query
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

//        Obtain according to the name of the group to obtain the information after group aggregation
        Terms terms = search.getAggregations().get("by_age");
        for(Terms.Bucket  entity:terms.getBuckets()){
            Object key = entity.getKey();
            long docCount = entity.getDocCount();
            System.out.println(key+"@"+docCount);
        }

Total score after grouping


The following is the sum of each person's score after grouping by name

//        Object to create query criteria
        SearchSourceBuilder searchSourceBuilder = 
        new SearchSourceBuilder();

//        Group by name
        TermsAggregationBuilder nameaggration = 
        AggregationBuilders.terms("by_name").field("name");
//        Sum by fraction
        SumAggregationBuilder field = 
        AggregationBuilders.sum("by_score").field("score");
Join two aggregate objects
        nameaggration.subAggregation(field);
        
        searchSourceBuilder
//                 .query(QueryBuilders.multiMatchQuery("jing","name","age"))
                .query(QueryBuilders.matchAllQuery())
                .aggregation(nameaggration);

Get results, that is, get everyone's achievements and achievements

//        Make a query
        SearchResponse search = 
        client.search(searchRequest, RequestOptions.DEFAULT);


        Terms nameterms = search.getAggregations().get("by_name");

        for(Terms.Bucket  entity:nameterms.getBuckets()){
            Sum sum = entity.getAggregations().get("by_age");
            System.out.println("and:"+sum);
        }

Multi index, multi type query

//        Put the query object into the request object
        searchRequest.source(searchSourceBuilder);


//     You can set the requested index in either of the following ways
        searchRequest.indices("test3","test2");
        searchRequest.indices("test*");

//        Set the type of request
        searchRequest.types("_doc","class");
        searchRequest.types("_doc*");
//        Set query type
        searchRequest.searchType(SearchType.QUERY_THEN_FETCH);

Pole number query

Posted by bakigkgz on Tue, 21 Sep 2021 23:09:37 -0700