Elasticsearch 增删改查,分页(二)

环境:JDK 1.8、ES 7.x

一、新增:

1.JPA:

    public ItemDoc create(ItemDoc itemDoc) {

        ItemDoc itemDoc0 = itemRepository.save(itemDoc);
        log.info("itemDoc:{}" + itemDoc0.toString());
        return itemDoc0;
    }

2.模板:

    public void create(ItemDoc itemDoc) {

        IndexQuery indexQuery = new IndexQuery();
        indexQuery.setId(itemDoc.getId()+"");//id
        indexQuery.setObject(itemDoc);//doc 文档
        IndexCoordinates coordinates = IndexCoordinates.of("item");//索引
        elasticsearchTemplate.index(indexQuery, coordinates);
    }

二、修改:

部分字段更新


    public void update(ItemDoc itemDoc) {

        Map map = bean2Map(ItemDoc, true);//随便找个工具将对象转成map
        Document document = Document.from(map);
        IndexCoordinates coordinates = IndexCoordinates.of("item");
        UpdateQuery updateQuery = UpdateQuery.builder(itemDoc.getId() + "")
            .withDocument(document)
            .build();
        elasticsearchTemplate.update(updateQuery, coordinates);
    }

三、删除:

1.JPA:

    public void delete(ItemDoc itemDoc) {
        itemRepository.deleteById(itemDoc.getId());
        log.info("删除成功,id:{}", itemDoc.getId());
    }

2.模板:

    public void delete(ItemDoc itemDoc) {
        IndexCoordinates coordinates = IndexCoordinates.of("item");
        elasticsearchTemplate.delete(itemDoc.getId() + "", coordinates);
        log.info("删除成功,id:{}", itemDoc.getId());
    }

四、查询:

1.JPA:

/**
 * 
 * 参考CrudRepository或者自条件来查询
 * 无法满足复杂条件查询
 * 
 **/
public ItemDoc queryById(Long id){
    Optional itemDocOptional = itemRepository.findById(id);
    return itemDocOptional.orElse(null);
}

2.模板:

    public List queryByParam(ItemInnerParam innerParam) {

        BoolQueryBuilder query = boolQuery();

        //条件参数构造
        //ReflectionBuildESUtils.buildEqual(innerParam, ItemDoc.class, query);

        log.info("构建ES查询参数,queryParam:{}", JSONObject.toJSONString(innerParam));

        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("id").order(SortOrder.DESC);

        //filter比query快
        /**
         * query的时候,会先比较查询条件,然后计算分值,最后返回文档结果;
         * 而filter则是先判断是否满足查询条件,如果不满足,会缓存查询过程(记录该文档不满足结果);
         * 满足的话,就直接缓存结果
         * 综上所述,filter快在两个方面:
         *     1.对结果进行缓存
         *     2.避免计算分值
         */
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withSort(sortBuilder)
            .withFilter(query)
            //.withQuery(query)
            .build();

        SearchHits searchHits = elasticsearchTemplate.search(searchQuery,
            ItemDoc.class,
            IndexCoordinates.of("item"));

        List templateDocs = searchHits.stream().map(SearchHit::getContent).collect(
            Collectors.toList());

        return templateDocs;
    }


五、分页:

模板查询:

    public PageResult listPage(ItemInnerParam innerParam) {
        BoolQueryBuilder query = boolQuery();

        //条件参数构造
        //ReflectionBuildESUtils.buildEqual(innerParam, ItemDoc.class, query);

        log.info("构建ES查询参数,queryParam:{}", JSONObject.toJSONString(innerParam));

        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("id").order(SortOrder.DESC);

        //filter比query快
        /**
         * query的时候,会先比较查询条件,然后计算分值,最后返回文档结果;
         * 而filter则是先判断是否满足查询条件,如果不满足,会缓存查询过程(记录该文档不满足结果);
         * 满足的话,就直接缓存结果
         * 综上所述,filter快在两个方面:
         *     1.对结果进行缓存
         *     2.避免计算分值
         */
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withSort(sortBuilder)
            .withFilter(query)
            //.withQuery(query)
            .withPageable(PageRequest.of(innerParam.getPageIndex() - 1, innerParam.getPageSize()))
            .build();

        SearchHits searchHits = elasticsearchTemplate.search(searchQuery,
            ItemDoc.class,
            IndexCoordinates.of("item"));

        List templateDocs = searchHits.stream().map(SearchHit::getContent).collect(
            Collectors.toList());

        PageResult pageResult = new PageResult<>();
        pageResult.setTotal(searchHits.getTotalHits());
        pageResult.setDatas(templateDocs);
        return pageResult;
    }

六、结尾

整体来说还属于比较简单, 比较适合新手或者说没咋接触过的同学. 有些场景需要批量操作的没有列出来, 但是模板里有对应的api, 难度差不多所以没有全列出来!

你可能感兴趣的:(Elasticsearch 增删改查,分页(二))