Elasticsearch-Java高级API的简单使用

package com.corecmd.webapp.tiansjportal;

import com.alibaba.fastjson.JSON;
import com.corecmd.webapp.tiansjportal.common.enums.ResourceTypeEnum;
import com.corecmd.webapp.tiansjportal.common.utils.DateUtil;
import com.corecmd.webapp.tiansjportal.elasticsearch.domain.ResUserSearchVO;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;


@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class ElasticsearchTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 判断索引是否存在
     */
    @Test
    public void getIndex() {
        try {
            String indexName = "logstash-system-localhost-2021.10.31";
            GetIndexRequest re = new GetIndexRequest(indexName);
            boolean isExist = restHighLevelClient.indices().exists(re, RequestOptions.DEFAULT);
            log.info("索引:{}是否存在:{}", indexName, isExist);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void createIndex() {
        try {
            String indexName = "tiansjportal-user-file-search";
            log.info("创建索引:" + indexName);
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
            CreateIndexResponse response = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            log.info("创建索引结果:" + response.isAcknowledged());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void deleteIndex() {
        try {
            String indexName = "tim_user_search_his";
            log.info("删除索引:" + indexName);
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
            AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            log.info("删除索引结果:" + delete.isAcknowledged());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建文档
     * 批量插入文档时,需要建立BulkRequest,并向BulkRequest中add IndexRequest
     * 最后:restHighLevelClient.bulk()发生请求
     */
    @Test
    public void createDoc() {
        try {
            String indexName = "tiansjportal-user-video-search";
            log.info("向索引:{}中添加文档", indexName);
            ResUserSearchVO userSearchVO = new ResUserSearchVO();
            userSearchVO.setUserId(7);
            userSearchVO.setKeyWord("杨");
            userSearchVO.setResourceType(ResourceTypeEnum.ALBUM.getTypeEn());
            userSearchVO.setSearchTime(DateUtil.getDateStr(new Date(), DateUtil.DATE_TIME_FORMAT));
            String jsonType = JSON.toJSONString(userSearchVO);
            log.info("文档数据:{}", jsonType);
            IndexRequest indexRequest = new IndexRequest(indexName);
            indexRequest.source(jsonType, XContentType.JSON);
            IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            log.info("文档创建结果:" + DocWriteResponse.Result.CREATED.equals(response.getResult()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //更新文档
    @Test
    public void updateDoc() {
        try {
            String indexName = "tiansjportal-user-album-search";
            log.info("在索引:{}中更新文档", indexName);
            ResUserSearchVO userSearchVO = new ResUserSearchVO();
            userSearchVO.setUserId(7);
            userSearchVO.setKeyWord("祖国风景");
            userSearchVO.setResourceType(ResourceTypeEnum.ALBUM.getTypeEn());
            userSearchVO.setSearchTime(DateUtil.getDateStr(new Date(), DateUtil.DATE_TIME_FORMAT));
            String jsonType = JSON.toJSONString(userSearchVO);
            log.info("文档数据:{}", jsonType);
            UpdateRequest updateRequest = new UpdateRequest(indexName, "peRS1HwBv8L2V11VN_8F");
            updateRequest.doc(jsonType, XContentType.JSON);
            //获取修改后的结果
            updateRequest.fetchSource(true);
            UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            log.info("文档更新结果:" + DocWriteResponse.Result.UPDATED.equals(response.getResult()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除文档
    @Test
    public void deleteDoc() {
        try {
            String indexName = "tiansjportal-user-album-search";
            log.info("在索引:{}中删除文档", indexName);
            DeleteRequest deleteRequest = new DeleteRequest(indexName, "peRS1HwBv8L2V11VN_8F");
            DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            log.info("文档更新结果:" + DocWriteResponse.Result.DELETED.equals(response.getResult()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询文档,根据文档id查询
    @Test
    public void searchDoc() {
        try {
            String indexName = "tiansjportal-user-album-search";
            log.info("在索引:{}中查询文档", indexName);
            GetRequest getRequest = new GetRequest(indexName, "oORN1HwBv8L2V11VQP9L");
            GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            if (response.isExists()) {
                log.info("文档查询结果:" + response.toString());
            } else {
                log.info("文档不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自定义查询,指定查询字段
     */
    @Test
    public void customSearch() {
        try {
            String indexName = "tiansjportal-user-album-search";
            log.info("在索引:{}中查询文档", indexName);
            SearchRequest searchRequest = new SearchRequest(indexName);
            //构建查询参数
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("keyWord", "杨");
            TermQueryBuilder resourceType = QueryBuilders.termQuery("resourceType", ResourceTypeEnum.ALBUM.getTypeEn());
            TermQueryBuilder author = QueryBuilders.termQuery("userId", "8");
            //查询参数构造器
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //向构造器添加参数
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.filter(matchQueryBuilder);
            boolQueryBuilder.filter(resourceType);
            boolQueryBuilder.filter(author);
            searchSourceBuilder.query(boolQueryBuilder);
            //设置请求查询擦书
            searchRequest.source(searchSourceBuilder);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //可能有多条结果
            if (response.getHits().getTotalHits().value > 0) {
                for (SearchHit searchHit : response.getHits().getHits()) {
                    log.info("查询结果:" + searchHit.getSourceAsString());
                }
            } else {
                log.info("没有查询到数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值