Elasticsearch operation notes

Sort related:

GET people/_search

{
    "query":{
        "match":{
            "name":"zhangsan"
        }
    },
    "sort":[
        {
        	"price":{
                "order":"desc"
            }
    	}
    ]
}

After the query, add a set, sort, to specify the sorting rule, that is, the sorting attribute, order or flashback

java code related query sorting:

sourceBuilder.sort("price", SortOrder.ASC).sort("a",SortOrder.ASC);
//Chain programming, you can add sorting rules

Document operation

//Query documents by id
        GetRequest getRequest = new GetRequest("people","id");
        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        String sourceAsString = documentFields.getSourceAsString();

//Add or modify documents
        Object o = new Object();
        String s = JSON.toJSONString(o);
        IndexRequest indexRequest= new IndexRequest("Index name").id("asd").source(s, XContentType.JSON);
        IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);

        //remove document
        DeleteRequest deleteRequest= new DeleteRequest("Index name","id");
        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);

matchAll query:

Query all documents

  1. http://192.168.23.129:9200/people/_doc /Index name/_ Doc query all by default

  2. JAVA API operation:

     //Construct the query request object, and the construction method parameter is the index name
            SearchRequest searchRequest = new SearchRequest("people");
    
            //Query condition constructor
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    
            //Specify query criteria
            QueryBuilder query = QueryBuilders.matchAllQuery();
    
            sourceBuilder.query(query);
    
            searchRequest.source(sourceBuilder);
    
    
            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
    
            SearchHits hits = search.getHits();
            TotalHits totalHits = hits.getTotalHits();
    
            long value = totalHits.value;
            System.out.println(value);
            SearchHit[] hits1 = hits.getHits();
    
            for (SearchHit s :hits1){
                String sourceAsString = s.getSourceAsString();
                System.out.println(sourceAsString);
    
            }
    

    Summary: there is actually a nested process. When a client initiates a request, it needs to pass in a searchrequest. In the searchrequest, it needs to pass in a sourcebuilder. This builder can use the query method to specify various query methods and then specify various parameters. Paging information can also be added to sourcebuilder

term query:

For term query, word segmentation will not be performed on the query criteria

match query:

Equivalent matching after score

Script operation - 1:
GET people/_search

{
    "query":{
        "match":{
            "name":"zhangsan"
        }
    }
}
Script operation - 2
GET people/_search

{
    "query":{
        "match":{
            "name":{
                "query":"lisi",
                "operator":"and" --The default here is or,That is, the union of participle and non participle,and It means taking intersection
            }
        }
    }
}
JAVA-API operation:
@Test
    public void matchQuery() throws IOException {
        //Construct the query request object, and the construction method parameter is the index name
        SearchRequest searchRequest = new SearchRequest("people");

        //Query condition constructor
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //Specify query criteria
        MatchQueryBuilder query = QueryBuilders.matchQuery("key", "val");
        query.operator(Operator.OR);//Specify intersection or union
        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        long value = totalHits.value;
        System.out.println(value);
        SearchHit[] hits1 = hits.getHits();

        for (SearchHit s :hits1){
            String sourceAsString = s.getSourceAsString();
            System.out.println(sourceAsString);

        }
    }

Fuzzy query - wildcard query:

After word segmentation of query conditions, fuzzy matching is carried out

Script operation:

GET people/_search

{
    "query":{
        "wildcard":{
            "name":{
                "value":"Lee*"  ---Start with Lee,?0 Or 1,*,Multiple
            }
        }
    }
}

JAVA -API operation:

//Construct the query request object, and the construction method parameter is the index name
        SearchRequest searchRequest = new SearchRequest("people");

        //Query condition constructor
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //Specify query criteria
        WildcardQueryBuilder query = QueryBuilders.wildcardQuery("name", "Lee*");

        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        long value = totalHits.value;
        System.out.println(value);
        SearchHit[] hits1 = hits.getHits();

        for (SearchHit s :hits1){
            String sourceAsString = s.getSourceAsString();
            System.out.println(sourceAsString);

        }

Fuzzy query regular query

Regular query

Script operation:

GET people/_search

{
    "query":{
        "regexp":{
            "name":"\\w+(.)*"  --Search regular
        }
    }
}

JAVA-API operation:

//Construct the query request object, and the construction method parameter is the index name
        SearchRequest searchRequest = new SearchRequest("people");

        //Query condition constructor
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //Specify query criteria
        RegexpQueryBuilder query = QueryBuilders.regexpQuery("name", "Lee*");

        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        long value = totalHits.value;
        System.out.println(value);
        SearchHit[] hits1 = hits.getHits();

        for (SearchHit s :hits1){
            String sourceAsString = s.getSourceAsString();
            System.out.println(sourceAsString);

        }

Fuzzy query - prefix query:

prefix query

Script operation:

GET people/_search

{
    "query":{
        "prefix":{
            "name":{
                "value":"Li Si"   --Query the information beginning with Li Si,It seems that the data after the space will be counted
            }
        }
    }
}

JAVA-API operation:

//Construct the query request object, and the construction method parameter is the index name
        SearchRequest searchRequest = new SearchRequest("people");

        //Query condition constructor
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //Specify query criteria
        PrefixQueryBuilder query = QueryBuilders.prefixQuery("name", "Lee");
        
        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        long value = totalHits.value;
        System.out.println(value);
        SearchHit[] hits1 = hits.getHits();

        for (SearchHit s :hits1){
            String sourceAsString = s.getSourceAsString();
            System.out.println(sourceAsString);

        }

Range query:

Range query

Script operation:

GET people/_search

{
    "query":{
        "range":{
            "name":{
                "gte":2000,  --minimum value
                "lte":3000	--Maximum
            }
        }
    }
}

JAVA-API operation:

    @Test
    public void rangeSearch() throws IOException {
        //Construct the query request object, and the construction method parameter is the index name
        SearchRequest searchRequest = new SearchRequest("people");

        //Query condition constructor
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //Specify query criteria and query affixes
        RangeQueryBuilder query = QueryBuilders.rangeQuery("price");

        query.gte(2000);//lower limit
        query.lte(3000);//go online

        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        long value = totalHits.value;
        System.out.println(value);
        SearchHit[] hits1 = hits.getHits();

        for (SearchHit s :hits1){
            String sourceAsString = s.getSourceAsString();
            System.out.println(sourceAsString);

        }
    }

queryString query

Description:

You can specify multiple fields to query a specific value For example, Li can be queried from name or addr at the same time

Script operation:

#GET people/_search

{
    "query":{
        "query_string":{
            "fields":["name","addr","age"],
            "query":"Lee AND four"  #OR, custom word segmentation, AND, force merge, no word segmentation
        }
    }
}
# The second operation mode
{
    "query":{
        "simple_query_string":{
            "fields":["name","addr","age"],
            "query":"Lee AND four"  #Custom OR AND do not work AND are treated as a common word
        }
    }
}

Java API operation

//Construct the query request object, and the construction method parameter is the index name
        SearchRequest searchRequest = new SearchRequest("people");

        //Query condition constructor
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //Specify query criteria and query affixes
        QueryStringQueryBuilder query = QueryBuilders.queryStringQuery("Lee").field("name").field("addr").defaultOperator(Operator.AND);


        sourceBuilder.query(query);
        sourceBuilder.sort("price", SortOrder.ASC).sort("a",SortOrder.ASC);

        searchRequest.source(sourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        long value = totalHits.value;
        System.out.println(value);
        SearchHit[] hits1 = hits.getHits();

        for (SearchHit s :hits1){
            String sourceAsString = s.getSourceAsString();
            System.out.println(sourceAsString);

        }

Boolean query

Description:

You can connect multiple queries

Query classification:

  1. Must query: the condition must be true (and)
  2. must_not: the condition must not be true (not)
  3. should: the condition can be established
  4. filter: the condition must be true. The performance is better than must. The score is removed

Script operation:

#GET people/_search
{
    "query":{
        "bool":{
            "must":[{}],
            "filter":[{}],
            "must_not":[{}],
            "should":[{}]
        }
    }
}
#Example:
{
    "query":{
        "bool":{
            "must":[{
                "term":{
                    "brand":{
                        "value":"Huawei"
                    }
                }
            }],
            "filter":[{
                "range":{
            		"name":{
                		"gte":2000,  --minimum value
                		"lte":3000	--Maximum
            		}
        		}
            }],
            "must_not":[{}],
            "should":[{}]
        }
    }
}

JAVA-API operation:

@Test
    public void boolQuery() throws IOException {
        //Construct the query request object, and the construction method parameter is the index name
        SearchRequest searchRequest = new SearchRequest("people");

        //Query condition constructor
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //Specify query criteria and query affixes
        BoolQueryBuilder query = QueryBuilders.boolQuery();

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("a", "b");
        query.must(termQueryBuilder);

        RangeQueryBuilder price = QueryBuilders.rangeQuery("price");
        price.gte(2000);
        price.lte(3000);
        query.should(price);
        sourceBuilder.query(query);
        sourceBuilder.sort("price", SortOrder.ASC).sort("a",SortOrder.ASC);

        searchRequest.source(sourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        long value = totalHits.value;
        System.out.println(value);
        SearchHit[] hits1 = hits.getHits();

        for (SearchHit s :hits1){
            String sourceAsString = s.getSourceAsString();
            System.out.println(sourceAsString);

        }
    }

Explanation: in fact, it is to construct a boolquery object and put other query objects into the database

Aggregate query:

Description:

  1. Index aggregation: aggregation functions in mysql, such as max,min,avg,sum, etc
  2. Bucket aggregation: equivalent to group by aggregation in mysql. text types cannot be grouped and will fail

Script operation:

#GET people/_search

#Indicator aggregation:
{
    "query":{
        "match":{
            "name":"Zhang San"
        }
    },
    "aggs":{
        "NAME":{	#The NAME here is the key that encapsulates the aggregation result after aggregation query, which can be customized
            "max":{
                "field":"price"
            }
        }
    }
}

#Barrel polymerization
{
    "query":{
        "match":{
            "name":"Zhang San"
        }
    },
    "aggs":{
        "NAME":{	#The NAME here is the key that encapsulates the aggregation result after aggregation query, which can be customized
            "terms":{ 	#Indicates the grouping operation terms
                "field":"price",
                "size":200
            }
        }
    }
}

‚Äč

Tags: ElasticSearch search engine

Posted by ineedhelp on Sat, 16 Apr 2022 16:44:25 +0930