89_熟练掌握ES Java API_对汽车品牌进行多种条件的组
2020-03-04 本文已影响0人
小山居
89_熟练掌握ES Java API_对汽车品牌进行多种条件的组合搜索
多种搜索结合一起搜索---must--mustnot--should--filter
QueryBuilder qb = boolQuery()
.must(matchQuery("brand", "宝马"))
.mustNot(termQuery("name.raw", "宝马318"))
.should(termQuery("produce_date", "2017-01-02"))
.filter(rangeQuery("price").gte("280000").lt("350000"));
SearchResponse response = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(qb)
.get();
源代码 BoolQuerySearchBrand
public class BoolQuerySearchBrand {
@SuppressWarnings({ "resource", "unchecked" })
public static void main(String[] args) throws Exception {
Settings settings = Settings.builder()
.put("cluster.name", "elasticsearch")
.build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("brand", "宝马"))
.mustNot(QueryBuilders.termQuery("name.raw", "宝马318"))
.should(QueryBuilders.rangeQuery("produce_date").gte("2017-01-01").lte("2017-01-31"))
.filter(QueryBuilders.rangeQuery("price").gte(280000).lte(350000));
SearchResponse searchResponse = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(queryBuilder)
.get();
for(SearchHit searchHit : searchResponse.getHits().getHits()) {
System.out.println(searchHit.getSourceAsString());
}
client.close();
}
}