深入了解ES搜索

ES通用dao

@Slf4j
@Service
public class ElasticSearchDAO {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 判断索引是否存在
     * @param indexName
     * @return
     * @throws IOException
     */
    public boolean existsIndex(String indexName) throws IOException {
        GetIndexRequest request = new GetIndexRequest(indexName);
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        log.info("{} exists:{}",indexName,exists);
        return exists;
    }

    /**
     * 创建索引
     * @param indexName
     * @throws IOException
     */
    public void createIndex(String indexName) throws IOException {
        CreateIndexRequest createRequest = new CreateIndexRequest(indexName);
        CreateIndexResponse response = client.indices().create(createRequest, RequestOptions.DEFAULT);
        log.info("{}创建成功 {}",indexName, JSON.toJSON(response));
    }

    /**
     * 删除索引
     * @param indexName
     * @throws IOException
     */
    public void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        log.info("{}删除成功 {}",indexName, JSON.toJSON(response));
    }

    /**
     * 批量插入数据
     */
    public void insertBatch(String indexName, List<ElasticEntity> list) throws IOException {
        BulkRequest request = new BulkRequest();
        list.forEach(item -> request.add(new IndexRequest(indexName).id(item.getId())
                .source(JSONUtil.toJSON(item.getData()), XContentType.JSON)));
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        log.info("{}批量插入数据成功 {}",indexName, JSON.toJSON(response));
    }
    
    /**
     * 添加或更新数据
     */
    public void saveOrUpdate(String indexName,ElasticEntity entity) throws IOException {
        IndexRequest request = new IndexRequest(indexName);
        request.id(entity.getId());
        request.source(JSONUtil.toJSON(entity.getData()), XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        log.info("{}添加或更新数据成功 {}",indexName, JSON.toJSON(response));
    }

    /**
     * 通过id批量删除
     */
    public <T> void deleteBatch(String indexName, Collection<T> idList) throws IOException {
        BulkRequest request = new BulkRequest();
        idList.forEach(item -> request.add(new DeleteRequest(indexName, item.toString())));
        BulkResponse response = client.bulk(re
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值