Es查询

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);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章