1. term、terms、match、match_all、match_phrase查詢
term: 對查詢字段進行精確匹配,不分詞,建議不要對text類型的字段使用;
terms: 與term類似,不過查詢字段可以包含多個單詞,使用json數組;
match: 對輸入內容進行分詞,然後對指定的text類型字段進行匹配,可以對非text類型使用;
match_all: 查詢所有;
match_phrase: 不對輸入內容分詞,將整個短語對指定的text類型字段進行匹配;
2. bool查詢
布爾查詢是一種聯合查詢,可以對多個查詢條件進行組合,布爾查詢有四個子查詢關鍵詞: should、filter、must、must_not
3. should、filter、must、must_not查詢
must: 查詢的結果必須匹配查詢條件,並計算score
filter: 查詢的結果必須匹配查詢條件,和must不同不會計算score
should: 查詢結果必須符合查詢條件中的一個或多個;
must_not: 查詢結果必須不符合查詢條件
關於should和must聯用的說明:
should和must一起用,should會失效,加上minimum_should_match 就可以了,或者使用bool再嵌套一層;
當使用should查詢時,如果包含了must或者filter查詢,
那麼should的查詢語句就不是或者的意思了,而是有或者沒有都行的含義
4. size、sort
{
"query":{
"bool":{}
},
"size":10,
"sort":{
"非text類型字段":"desc/asc"
}
/*
"sort":{
"非text類型字段":{
"order":"desc/asc"
}
}
*/
}
5. 常用查詢
# 查詢所有索引
curl -XGET http//${ip}:9200/_cat/indices
# 查詢指定索引mapping
curl -XGET http://${ip}:9200/${index}/_mappings
# 查詢指定索引數據
curl -XGET http://${ip}:9200/${index}/_search?pretty
# 根據id查詢指定索引數據
curl -XGET http://${ip}:9200/${index}/${type}/${_id}
# queryString查詢
curl -XGET http://${ip}:9200/${index}/_search?q=${key}:"${value}"
# 根據請求體查詢
curl -X GET "http://${ip}:9200/${index}/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {}
}
}
'
6. 使用ElasticsearchRepository操作ES
//1. 創建實體類,使用@Document註解,指定索引名
//@Document -> package org.springframework.data.elasticsearch.annotations;
@Document(indexName = "${index}")
public class EsEntity {
}
//2. 編寫接口繼承ElasticsearchRepository並指定實體類泛型,和id類型,並通過@Component註解注入容器管理
@Component
public interface EsEntityRepository extends ElasticsearchRepository<EsEntity, String> {
}
//3. service層調用查詢、插入方法,這裏省去EsEntityService接口代碼
@Service
public class EsEntityServiceImpl implements EsEntityService {
@Autowired
EsEntityRepository esEntityRepository;
/**
* 查詢
*/
@Override
public Page<EsEntity> queryEsEntityList() {
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
//設置bool查詢條件等
//排序
FieldSortBuilder fieldSortBuilder = new FieldSortBuilder("${排序字段}");
fieldSortBuilder.order(SortOrder.DESC);
nativeSearchQueryBuilder.withSort(fieldSortBuilder);
//分頁查詢
Pageable pageable = PageRequest.of("${pageNo}","${pageSize}");
nativeSearchQueryBuilder.withPageable(pageable);
//執行查詢
Page<PubJqClGpsEs> search = esEntityRepository.search(nativeSearchQueryBuilder.build());
return search;
}
/**
* 插入
*/
@Override
public void saveEsEntity(EsEntity esEntity) {
esEntityRepository.save(esEntity);
}
}