Elasticsearch combat-advanced query

Elasticsearch combat-advanced query

1. Compound query

Compound query is to combine some simple queries to achieve more complex query requirements. In addition, compound query can also control the behavior of another query.

1.1 constant_score

constant_scorequery can wrap a query of other types and return documents that match the query conditions in the filter and have the same score. When we don’t care about the impact of search term frequency on the ranking of search results, we can use constant_scoreto wrap query statements queryor filter statements filter.

Examples are as follows:

{
    
    
    "query":{
    
    
        "constant_score":{
    
    
        	"filter":{
    
    
        		"term":{
    
    
        			"city":"北京市"
        		}
        	}
        }
    }
}

The java example is as follows:

MatchQueryBuilder query = QueryBuilders.matchQuery("title", "新闻").minimumShouldMatch("90%");
QueryBuilders.constantScoreQuery(query).boost(3.0f);

1.2 bool query

boolQueries can be any number of simple queries together using must, should, must_not, filteroption represents a simple query logic between each option can appear anywhere from zero to many times their meanings are:

  • must: The document must matchmust the query conditions under the option, which is incompatible with logical operators AND.
  • should: The document can matchshould the query conditions under the option or not match , which is incompatible with logical operations OR.
  • must_not: mustOn the contrary, documents matching the query conditions under this option will not be returned .
  • filtermustSame as the same, the documents matching filterthe query conditions under the option will be returned , but they will not be filterscored and only serve as a filtering function.

Examples are as follows:

{
    
    
    "query":{
    
    
    	"bool":{
    
    
    		"must":[
    			{
    
    
    				"match":{
    
    
    					"title":"共享单车"
    				}
    			},
    			{
    
    
    				"term":{
    
    
    					"district":"昌平区"
    				}
    			}
    		],
    		"should":[
    			{
    
    
    				"match":{
    
    
    					"address":"朝阳区"
    				}
    			}	
    		]
    	}
    }
}

1.3 dis_max query

dis_max query and bool query have certain connections and differences. dis_max query supports multiple concurrent queries and can return document types that match any query clause. Unlike the way that bool query can combine the scores of all matching queries, dis_max query only uses the scores of the best query conditions.

{
    
    
    "query":{
    
    
    	"dis_max":{
    
    
			"tie_breaker":0.7,
			"boost":1.2,
			"queries":[
				{
    
    
					"match":{
    
    "address":"北京朝阳区"}
				},
				{
    
    
					"match":{
    
    
						"title":"北京朝阳区"
					}
				}
			]
    	}
    }
}

1.4 function_score query

The function_score query can modify the document score of the query. This query is very useful in some cases. For example, it is more expensive to calculate the document score through the scoring function. You can use a filter plus a custom scoring function to replace the traditional scoring method.

To use function_score query, the user needs to define a query and one or more scoring functions. The scoring function will calculate the score for each document in the query.

{
    
    
  "query": {
    
    
    "function_score": {
    
    
      "query": {
    
    
        "function_score": {
    
    
          "query": {
    
    
            "match": {
    
    
              "title": "java编程"
            }
          },
          "functions": [
            {
    
    
              "field_value_factor": {
    
    
                "field": "price",
                "factor": 0.1,
                "modifier": "ln1p"
              }
            }
          ],
          "score_mode": "multiply",
          "max_boost": 10,
          "boost": 1
        }
      },
      "functions": [],
      "score_mode": "multiply",
      "boost_mode": "sum",
      "max_boost": 10,
      "boost": 1
    }
  }
}

The java example is as follows:

MatchPhraseQueryBuilder titleQuery = QueryBuilders.matchPhraseQuery("title", "java编程");
FieldValueFactorFunctionBuilder factor = ScoreFunctionBuilders.fieldValueFactorFunction("price").modifier(FieldValueFactorFunction.Modifier.LN1P).factor(0.1f);
FunctionScoreQueryBuilder.FilterFunctionBuilder[] filterFunctionBuilders = {
    
    
    new FunctionScoreQueryBuilder.FilterFunctionBuilder(factor)
};
FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(titleQuery,filterFunctionBuilders);
FunctionScoreQueryBuilder query = QueryBuilders.functionScoreQuery(functionScoreQuery).boostMode(CombineFunction.SUM);

Detailed scoring function

1.5 boosting query

boostingThe query is used in scenarios where the scores of two queries need to be adjusted. The boostingquery encapsulates the two queries and reduces the score of one of the queries.

boostingThe query includes positive, negativeand negative_boostthree parts, positivethe query score in the remains unchanged, negativethe query in will reduce the document score, negative_boostindicating the egativereduced weight in n .

The books that are inquired titlefor javaare listed 2018年之前at the back of the publication time .

{
    
    
    "query":{
    
    
        "boosting":{
    
    
            "positive":{
    
    
                "match":{
    
    
                    "title":"java"
                }
            },
            "negative":{
    
    
                "range":{
    
    
                    "publishAt":{
    
    
                        "lte":"2018-01-01"
                    }
                }
            },
            "negative_boost":0.2
        }
    }
}

The java example is as follows:

MatchPhraseQueryBuilder titleQuery = QueryBuilders.matchPhraseQuery("title", "java");
RangeQueryBuilder publishAt = QueryBuilders.rangeQuery("publishAt").lte("2018-01-01");
QueryBuilders.boostingQuery(titleQuery,publishAt).negativeBoost(0.2f);

2. Nested queries

2.1 Parent-child query

Here is an example of shops and commodities. They belong to different types, which are equivalent to two tables in the database. If you want to associate shops with the commodities they operate, you need to tell the parent-child relationship between the ES documents, and specify a field here. store2productTo maintain this relationship, the field type is join, and their relationship is specified.

2.1.1 Create parent-child relationship index

PUT store
{
    
    
  "mappings": {
    
    
    "properties": {
    
    
      "name": {
    
    
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "store2product": {
    
    
        "type": "join",
        "relations": {
    
    
          "storeid": "productid"
        }
      }
    }
  }
}

2.2.2 Adding a relationship document

Add a parent document (shop) and specify the parent field

PUT store/1
{
    
    
  "name":"创实食品专营店",
  "store2product":"storeid"
}

Add a child document (product), and the child document and the parent document need to be in the same shard, so you need to specify it 路由idas父id

PUT store/2?routing=1
{
    
    
  "name":"创实 原味酸梅汤 速溶酸梅粉 冲饮果汁饮料1000g 酸梅汤原料",
  "store2product":{
    
    
    "name":"productid",
    "parent":"1"
  }
}

2.2.3 Query the products under the store

Use has_parentquery and specify parent_typeasstoreid

GET store/_search
{
    
    
  "query": {
    
    
    "has_parent": {
    
    
      "parent_type": "storeid",
      "query": {
    
    
        "match": {
    
    
          "name": "食品专营店"
        }
      }
    }
  }
}

The java example is as follows:

MatchQueryBuilder nameQuery = QueryBuilders.matchQuery("name", "食品专营店");
HasParentQueryBuilder hasParentQueryBuilder = new HasParentQueryBuilder("storeid",nameQuery,true); 

2.2.4 Check which store the product belongs to

Use has_childquery and specify a typefield asproductid

GET store/_search
{
    
    
  "query": {
    
    
    "has_child": {
    
    
      "type":"productid",
      "query": {
    
    
        "match": {
    
    
          "name": "原味酸梅汤"
        }
      }
    }
  }
}

The java example is as follows:

MatchQueryBuilder nameQuery = QueryBuilders.matchQuery("name", "原味酸梅汤");
HasChildQueryBuilder hasChildQueryBuilder = new HasChildQueryBuilder("productid",nameQuery, ScoreMode.None);

3. Follow me

Search WeChat public account: the road to a strong java architecture
Insert picture description here

Guess you like

Origin blog.csdn.net/dwjf321/article/details/103934964