88_熟练掌握ES Java API_对汽车品牌进行全文检索、精
2020-03-04 本文已影响0人
小山居
88_熟练掌握ES Java API_对汽车品牌进行全文检索、精准查询和前缀搜索
添加数据
PUT /car_shop/cars/5
{
"brand": "华晨宝马",
"name": "宝马318",
"price": 270000,
"produce_date": "2017-01-20"
}
全文检索方法
SearchResponse response = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(QueryBuilders.matchQuery("brand", "宝马"))
.get();
多字段搜索multiMatch
SearchResponse response = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(QueryBuilders.multiMatchQuery("宝马", "brand", "name"))
.get();
termquery 方法
SearchResponse response = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(QueryBuilders.commonTermsQuery("name", "宝马320"))
.get();
前缀搜索api
SearchResponse response = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(QueryBuilders.prefixQuery("name", "宝"))
.get();
整体源码如下
public class FullTextSearchByBrand {
@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));
SearchResponse searchResponse = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(QueryBuilders.matchQuery("brand", "宝马"))
.get();
for(SearchHit searchHit : searchResponse.getHits().getHits()) {
System.out.println(searchHit.getSourceAsString());
}
System.out.println("====================================================");
searchResponse = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(QueryBuilders.multiMatchQuery("宝马", "brand", "name"))
.get();
for(SearchHit searchHit : searchResponse.getHits().getHits()) {
System.out.println(searchHit.getSourceAsString());
}
System.out.println("====================================================");
searchResponse = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(QueryBuilders.termQuery("name.raw", "宝马318"))
.get();
for(SearchHit searchHit : searchResponse.getHits().getHits()) {
System.out.println(searchHit.getSourceAsString());
}
System.out.println("====================================================");
searchResponse = client.prepareSearch("car_shop")
.setTypes("cars")
.setQuery(QueryBuilders.prefixQuery("name", "宝"))
.get();
for(SearchHit searchHit : searchResponse.getHits().getHits()) {
System.out.println(searchHit.getSourceAsString());
}
client.close();
}
}