一、ES查询
1)查询全部文档(type在es高版本被移除,非必须):
match_all:
GET /#{索引名(可加*匹配多个索引)}/#{type名(可用,分隔匹配多个类型)}/_search
{
"query": { "match_all": {} }
}
- 查询与过滤(type在es高版本被移除,非必须)
match查询:
GET /#{索引名}/#{type名}/_search
{
"query": {
"match": {
"#{字段名(即field名)}":"#{字段值}"
}
}
multi_match查询:
GET /#{索引名}/#{type名}/_search
{
"query": {
"multi_match":
{
"query":"#{字段值}",
"fields":["#{字段名1}","#{字段名2}"]
}
}
}
range查询:
GET /#{索引名}/#{type名}/_search
{
"query": {
"range": {
"#{字段名}": {
"gte": #{字段值大于等于}
}
"#{字段名}": {
"ge": #{字段值大于}
}
"#{字段名}": {
"le": #{字段值小于}
}
"#{字段名}": {
"lte": #{字段值小于等于}
}
}
}
}
term查询:
GET /#{索引名}/#{type名}/_search
{
"query": {
"term": {
"#{字段名}":"#{字段值}"
}
}
terms查询:
GET /#{索引名}/#{type名}/_search
{
"query": {
"terms": {
"#{字段名}":"[#{字段值1},#{字段值1},]"
}
}
二、基于jest中的searchbox的API查询方式
依赖包版本:io.searchbox:jest:6.3.1
1)通用查询:
public static final String INDEX_NAME = "...";
public static final String TYPE_NAME = "...";
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
String searchString = new SearchSourceBuilder()
.query(boolQueryBuilder)
.toString();
Search search = new Search.Builder(searchString).addIndex(INDEX_NAME).addType(TYPE_NAME).build();
SearchResult searchResult;
try {
searchResult = jestClient.execute(search);
//查询成功
if(searchResult.isSucceeded()){
//do something with searchResult
}
}catch(Exception e){
...
}
2)基于BoolQueryBuilder的子查询:
//查询
boolQueryBuilder.filter(QueryBuilders.termQuery(key, value));
//通配符查询
boolQueryBuilder.filter(QueryBuilders.wildcardQuery(key, "*" + value + "*"));
//范围小于查询
boolQueryBuilder.filter(QueryBuilders.rangeQuery(key).lt(value));
....
3)高亮
/**
* 高亮富文本
*/
private static final String PRE = "<em>";
private static final String POST = "</em>";
/** * 高亮设置
* @Author cx
* @param searchSourceBuilder
* @return void
*/
private void setHighlight(SearchSourceBuilder searchSourceBuilder){
//高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field(new HighlightBuilder.Field("字段一"));
highlightBuilder.field(new HighlightBuilder.Field("字段二"));
highlightBuilder.field(new HighlightBuilder.Field("字段三"));
highlightBuilder.preTags(PRE).postTags(POST);
searchSourceBuilder.highlighter(highlightBuilder);
}
4)排序
/**
* 排序参数设置
* @Author cx
* @param searchSourceBuilder
* @param operator asc升序;desc降序
* @param paramValue
* @return void
*/
private void setSorterParam(SearchSourceBuilder searchSourceBuilder, String operator, String param) {
param = param + ".keyword";
if (ASC.equals(operator)) {
searchSourceBuilder.sort(param, SortOrder.ASC);
} else if (DESC.equals(operator)) {
searchSourceBuilder.sort(param, SortOrder.DESC);
} else {
//throw new Exception("sorter参数格式不正确");
}
}
参考文档:
https://www.elastic.co/guide/cn/elasticsearch/guide/current/getting-started.html