Elasticsearch学习系列六(Es Java客户端操作)

x33g5p2x  于2022-07-01 转载在 ElasticSearch  
字(6.7k)|赞(0)|评价(0)|浏览(433)

说明:Es提供了多种不同的客户端:

  • TransportClient:传统客户端,预计8.0版本会下掉

  • RestClient:官方推荐,它又包括两种

  • Java Low Level REST Client

  • Java High Level REST Client

ES在6.0后提供Java High Level Rest Client,这两种官方更推荐使用High Level

接下来我们开始使用Java客户端进行操作。

环境搭建
  1. 引入依赖
<dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.3.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>7.3.0</version>
</dependency>
  1. 配置Es连接信息
@Configuration
public class ElasticsearchConfig {

    private String hosts = "192.168.56.115:9200";

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        String[] hostArray= new String[]{hosts};
        HttpHost[] httpHosts=new HttpHost[hostArray.length];
        for (int i=0;i<hostArray.length;i++){
            String host = hostArray[i];
            String[] split = host.split(":");
            httpHosts[i]=new HttpHost(split[0],Integer.valueOf(split[1]),"http");
        }
        return new RestHighLevelClient(RestClient.builder(httpHosts));

    }
}
ES API操作
  1. 创建索引
@Test
public void createIndex() throws IOException {
    CreateIndexRequest createIndexRequest=new CreateIndexRequest("es_java");
    //设置参数
    createIndexRequest.settings(Settings.builder().put("number_of_shards","1").put("number_of_replicas","0"));
    XContentBuilder xContentBuilder=XContentFactory.jsonBuilder()
            .startObject()
            .field("properties")
            .startObject()
            .field("description")
            .startObject().field("type","text")
            .field("analyzer","ik_max_word")
            .endObject()
            .field("name").startObject()
            .field("type","keyword")
            .endObject()
            .field("pic").startObject()
            .field("type","text")
            .field("index",false)
            .endObject()
            .field("studymodel")
            .startObject()
            .field("type","keyword")
            .endObject()
            .endObject().endObject();
    createIndexRequest.mapping(xContentBuilder);

    //操作索引的客户端
    IndicesClient indices = client.indices();
    CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
    boolean acknowledged = createIndexResponse.isAcknowledged();
    System.out.println("创建结果:"+acknowledged);

}

通过json的方式创建索引

@Test
    public void createIndexByJson() throws IOException {
        CreateIndexRequest createIndexRequest=new CreateIndexRequest("es_java");
        //设置参数
        createIndexRequest.settings(Settings.builder().put("number_of_shards","1").put("number_of_replicas","0"));
        createIndexRequest.mapping("{\n" +
                "    \"properties\": {\n" +
                "      \"description\": {\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"ik_max_word\"\n" +
                "      },\n" +
                "      \"name\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"pic\": {\n" +
                "        \"type\": \"text\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"studymodel\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      }\n" +
                "    }\n" +
                "  }.",XContentType.JSON);
        //操作索引的客户端
        IndicesClient indices = client.indices();
        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println("创建结果:"+acknowledged);
    }
  1. 删除索引
@Test
public void deleteIndex() throws IOException {
    DeleteIndexRequest deleteIndexRequest=new DeleteIndexRequest("es_java");
    IndicesClient indices = client.indices();
    AcknowledgedResponse acknowledgedResponse = indices.delete(deleteIndexRequest, RequestOptions.DEFAULT);
    System.out.println(acknowledgedResponse.isAcknowledged());

}
  1. 添加文档
@Test
public void testAddDoc() throws IOException {
    IndexRequest indexRequest=new IndexRequest("es_java","_doc");
    indexRequest.id("1");
    Map<String,Object> jsonMap=new HashMap<>();
    jsonMap.put("name","spring cloud实战");
    jsonMap.put("description","本课程主要从四个章节进行讲解: 1.微服务架构入门\n" +
            "2.spring cloud 基础入门 3.实战Spring Boot 4.注册中心eureka");
    jsonMap.put("studymodel","20001");
    jsonMap.put("name","spring cloud实战");
    jsonMap.put("pic","ttt.jpg");
    indexRequest.source(jsonMap);
    IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
    System.out.println(indexResponse.getResult());
}
  1. 查询文档
@Test
public void testGetDoc() throws IOException {
    GetRequest getRequest=new GetRequest("es_java","1");
    GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
    Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
    System.out.println(sourceAsMap);
}
  1. match搜索
@Test
public void testSearchAll() throws IOException {
    SearchRequest searchRequest=new SearchRequest("es_java");
    SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    seachDoc(searchRequest, searchSourceBuilder);

}

private void seachDoc(SearchRequest searchRequest, SearchSourceBuilder searchSourceBuilder) throws IOException {
    //第一个参数代表结果集包含什么字段,第二个参数代表结果集不包括哪些字段
    searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description","pic"},new String[]{});
    searchRequest.source(searchSourceBuilder);
    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

    //搜索结果
    SearchHits hits = searchResponse.getHits();
    //匹配的记录数
    TotalHits totalHits = hits.getTotalHits();
    for (SearchHit hit:hits){
        String id = hit.getId();
        //源文档内容
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        System.out.println("文档的id:"+id);
        System.out.println(sourceAsMap);
    }
}
  1. term搜索
@Test
public void testTermQuery() throws IOException {
    SearchRequest searchRequest=new SearchRequest("es_java");
    SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.termQuery("name","spring"));
    seachDoc(searchRequest,searchSourceBuilder);
}
  1. 分页搜索及排序
@Test
public void testSearchPage() throws IOException {
    SearchRequest searchRequest=new SearchRequest("es_java");
    SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
    searchSourceBuilder.from(0);
    searchSourceBuilder.size(2);
    searchSourceBuilder.sort("name",SortOrder.DESC);
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    seachDoc(searchRequest,searchSourceBuilder);
}

书山有路勤为径,学海无涯苦作舟

相关文章

最新文章

更多