简体   繁体   中英

querying on field missing from some document in elasticsearch

I have a special need where in I need to query elastic search for a field say F1. F1 is not there in all documents . My search should be for missing F1 documents and F1 with some value. F1 is missing or F1 = 'A1'

I am not sure if this is possible in elastic search. Here is my query and I know that is not right query. Would appreciate somebody could correct it or the Java program.

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "bool": {
          "must": [
            {
              "bool": {
                "should": {
                  "terms": {
                    "F1": [
                      "Some Value"
                    ]
                  }
                }
              }
            },
            {
              "missing": {
                "field": "F1"
              }
            }
          ]
        }
      }
    }
  }
}

This is my java code building the query.

  public QueryBuilder getQueryBuilder() {
        QueryBuilder qb;
        //what do we want to return if there is no request? Nothing or all.
        if (filters == null || filters.isEmpty()) {
            qb = QueryBuilders.matchAllQuery();
        } //build our filtered query using given filters in our request
        else {
            Set<String> keys = filters.keySet();
            BoolFilterBuilder boolFilterBuilder = FilterBuilders.boolFilter();
            for (String key : keys) {
                Set<Object> values = filters.get(key);
                if (values == null || values.toString().isEmpty()) {
                    continue; //Ignore nothing to do.
                }
                if (key.equalsIgnoreCase(Constants.MISSING_FILTER)) {
                    Iterator i = values.iterator();
                    while (i.hasNext()) {
                        boolFilterBuilder.must(FilterBuilders.missingFilter((String) i.next()));
                    }
                } else {
                    boolFilterBuilder.must(buildShouldQuery(key, values));
                }
            }
            qb = QueryBuilders.filteredQuery(createSearchQueryBuilder(), boolFilterBuilder);
        }
        return qb;
    }

Try whit this.

{
    "query": {
        "filtered": {
            "query": {
                "match_all": {}
            },
            "filter": {
                "bool": {
                    "should": [
                        { "terms": { "F1": ["Some Value"] },
                        { "missing": { "field": "F1" } }
                    ]
                }
            }
         }
     }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM