Query and filter for es

  elasticsearch

Query and filter merge

List filter’s api as deprecated and merge it into query. After that, the context of the query is divided into the context of the query and the context of the filter. If the context is not a filter, go to query’s context. Filter, the results will not participate in score calculation, and will be cached, which may be relatively fast.

Judging whether it belongs to filter context

  • the constant_score query

  • the must_not and (newly added) filter parameter in the bool query

  • the filter and filters parameters in the function_score query

  • any API called filter, such as the post_filter search parameter, or in aggregations or index aliases

Deprecated approach

{
    "query": {
        "filtered": {
            "filter": {
                "term": {
                    "year": 1961
                }
            }
        }
    }
}

Post-merger approach

{
    "query": {
        "bool": {
            "filter": {
                "term": {
                    "status": "active"
                }
            }
        }
    }
}

Bool, this way out score is 0, if add a match_all, score is 1

{
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "term": {
          "status": "active"
        }
      }
    }
  }
}

Constant_score method

{
    "query": {
        "constant_score": {
            "filter": {
                "term": {
                   "status": "active"
                }
            }
        }
    }
}

Constant_score, the default score is 1

The difference between match and term query

  • The mechanism of matchQuery is: first check whether the field type is analyzed; if so, segment the word before matching token; ; If not, the token is directly matched.

  • The mechanism of termQuery is to match token directly.

Special Treatment of Band-in value

such as

{
    "query": {
        "bool": {
            "filter": {
                "term": {
                    "status": "demo-active"
                }
            }
        }
    }
}

Value with-,will be cut by default, resulting in inaccurate search results. One of the solutions is to add a. raw to the field.

{
    "query": {
        "bool": {
            "filter": {
                "term": {
                    "status.raw": "demo-active"
                }
            }
        }
    }
}

On the Use of the Merged filter in java api

Json is the most direct way to use it, so you don’t have to use java api to translate it again.

String queryJson = "{\n" +
                "  \"query\": {\n" +
                "    \"constant_score\": {\n" +
                "      \"filter\": {\n" +
                "        \"term\": {\n" +
                "          \"status.raw\": \"demo-active\"\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}";
QueryBuilders.wrapperQuery(queryJson)

doc