JavaRestClient操作Elasticsearch中的source过滤

2022-12-21 09:12:23 浏览数 (1)

导包

导包可以根据 文档 里导入依赖

这里就不写依赖了

代码

默认情况下,索引库中所有数据都会返回,如果我们想只返回部分字段,可以通过source filter来控制

代码语言:javascript复制
import com.google.gson.Gson;
import com.leyou.pojo.Item;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EsdemoFindSource {

    private RestHighLevelClient client;

    private Gson gson = new Gson();
    /**
     * 先执行
     */
    @Before
    public void init (){
        // 初始化HighLevel客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        HttpHost.create("http://127.0.0.1:9201"),
                        HttpHost.create("http://127.0.0.1:9202"),
                        HttpHost.create("http://127.0.0.1:9203")
                )
        );
    }

    /**
     * source过滤查询
     */
    @Test
    public void findSource() throws IOException {
       //创建搜索对象
        SearchRequest searchRequest = new SearchRequest();
        //构建查询工具
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //添加查询条件,通过QueryBuilders获取各种查询
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        
        // 添加source过滤,只显示定义的字段,只存其一,用到时,将另一个注掉
        searchSourceBuilder.fetchSource(new String[]{"字段名", "字段名", "字段名"},null);
        // 添加source过滤,不显示定义的字段,,只存其一,用到时,将另一个注掉
        searchSourceBuilder.fetchSource(null,new String[]{"字段名", "字段名", "字段名"});

        searchRequest.source(searchSourceBuilder);
        //搜索
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        //解析
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit : hits) {
            //获取数据
            String shuju = hit.getSourceAsString();
            //反序列化
            Item item = gson.fromJson(shuju, Item.class);
            //打印
            System.out.println("结果:" item);
        }

    }

    /**
     * 后执行
     */
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

0 人点赞