ElasticSearch(三)原生Java操作

ElasticSearch(三)原生Java操作

  • 创建项目,添加对应的依赖,该依赖的版本与ES的版本要一致(我使用的是window的ES,避免了linux的连接问题,仅用于学习ES操作

<!--  原生JAVA操作ElasticSearch依赖  -->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.7.1</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.7.1</version>
</dependency>

  • 创建一个空索引

/**
 * 创建一个空索引
 */
@Test
public void createNullIndex() {
    RestHighLevelClient client = null;
    try {
        // 1、创建客户端请求,连接ElasticSearch
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建请求对象
        CreateIndexRequest request = new CreateIndexRequest("student");
        // 3、发起请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        // 4、操作响应结果
        System.out.println(response.index());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 5、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 创建一个有结构的索引

/**
 * 创建一个有结构的索引
 */
@Test
public void createMappingsIndex() {
    RestHighLevelClient client = null;
    try {
        // 1、创建一个客户端对象用于连接ES
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建一个请求对象
        CreateIndexRequest request = new CreateIndexRequest("teacher");
        request.source("{\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\":{\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"name\":{\n" +
                "        \"type\": \"text\"\n" +
                "      },\n" +
                "      \"desc\":{\n" +
                "        \"type\": \"text\"\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}", XContentType.JSON);
        // 3、发起请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        // 4、输出相应结果
        System.out.println(response.index());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 5、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 删除索引操作

@Test
public void deleteIndex() {
    RestHighLevelClient client = null;
    try {
        // 1、创建客户端对象
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("student");
        // 3、发起请求
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        // 4、输出响应结果
        System.out.println(response.isAcknowledged());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 5、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 新增文档操作

/**
 * 新增文档
 */
@Test
public void addDocument() {
    RestHighLevelClient client = null;
    try {
        // 1、创建客户端对象连接Es
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建请求对象
        IndexRequest request = new IndexRequest("teacher").id("4");
        // 3、添加文档的内容
        request.source(XContentFactory.jsonBuilder().startObject()
                .field("id",4)
                .field("name","懒羊羊")
                .field("desc","懒羊羊喜欢吃,还会骂美羊羊")
                .endObject()
        );
        // 4、发送请求
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        // 5、输出响应结果
        System.out.println(response.status());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 6、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 修改文档操作

/**
 * 修改文档:对于已存在的文档id进行保存就是修改
 */
@Test
public void updateDocument() {
    RestHighLevelClient client = null;
    try {
        // 1、创建客户端对象连接Es
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建请求对象
        IndexRequest request = new IndexRequest("teacher").id("1");
        // 3、添加文档的内容
        request.source(XContentFactory.jsonBuilder().startObject()
                .field("id",1)
                .field("name","update")
                .field("desc","updatemiaoshuxinxiupdate")
                .endObject()
        );
        // 4、发送请求
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        // 5、输出响应结果
        System.out.println(response.status());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 6、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 根据文档ID查询文档信息

/**
 * 根据文档ID查询文档信息
 */
@Test
public void findDocumentByID() {
    RestHighLevelClient client = null;
    try {
        // 1、创建客户端对象连接Es
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建请求对象
        GetRequest request = new GetRequest("teacher", "1");
        // 3、发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 4、输出文档信息
        System.out.println(response.getSourceAsString());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 5、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 删除文档信息

/**
 * 删除文档
 */
@Test
public void deleteDocumentByID() {
    RestHighLevelClient client = null;
    try {
        // 1、创建客户端对象连接Es
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建请求对象
        DeleteRequest request = new DeleteRequest("teacher", "1");
        // 3、发送请求
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        // 4、输出文档信息
        System.out.println(response.status());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 5、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 搜索所有文档

/**
 * 搜索所有文档
 * 前提先多添加几个文档信息
 */
@Test
public void findAllDocument() {
    RestHighLevelClient client = null;
    try {
        // 1、创建客户端对象连接Es
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        // 3、创建请求对象
        SearchRequest request = new SearchRequest("teacher").source(searchSourceBuilder);
        // 4、发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 5、输出查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 5、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 根据关键字搜索文档

/**
 * 根据关键子搜索文档
 */
@Test
public void findDocumentByKeywords() {
    RestHighLevelClient client = null;
    try {
        // 1、创建客户端对象连接Es
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        // 2、创建请求条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termQuery("desc","懒"));
        // 3、创建请求对象
        SearchRequest request = new SearchRequest("teacher").source(searchSourceBuilder);
        // 4、发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 5、输出查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 5、关闭客户端
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务