当前位置:   article > 正文

Java 操作ElasticSearch_elasticsearchclient java 使用

elasticsearchclient java 使用

        Java REST提供了两种风格的客户端连接工具,Java High Level REST Client、Java Low Level REST Client,这里我就不去细说Java Low Level REST Client了,因为这我确实没用到过,也不是很了解,我说一下Java High Level REST Client。

Java High Level REST Client ​​​​      

        首先如果你喜欢看官方文档的话,我把地址粘贴在这里,官网讲的也比较详细:Java High Level REST Client | Java REST Client [7.4] | Elastic

第一步添加依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-client -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.69</version>
        </dependency>

第二步:

在配置文件添加对应的地址以及端口:

elasticsearch:
  host: 127.0.0.1
  port: 9200

 第三步使用:

1.创建一个索引

  1. @Autowired
  2. private RestHighLevelClient client; //注入client、后面的代码会省略
  3. @Test
  4. public void addIndexAndmapping() throws IOException {
  5. IndicesClient indices = client.indices();
  6. //创建索引
  7. CreateIndexRequest createIndexRequest = new CreateIndexRequest("test_index");
  8. //设置分片数量以及副本数量
  9. createIndexRequest.settings(Settings.builder()
  10. .put("index.number_of_shards", 3)
  11. .put("index.number_of_replicas", 2)
  12. );
  13. //添加映射,相当于给表创建字段
  14. String mapping ="{properties={address={analyzer=ik_max_word, type=text}, name={type=keyword}, age={type=integer}}}";
  15. System.out.println(mapping);
  16. createIndexRequest.mapping(mapping, XContentType.JSON);
  17. CreateIndexResponse response = indices.create(createIndexRequest, RequestOptions.DEFAULT);//创建索引
  18. System.out.println(response.isAcknowledged());
  19. }

2.查询某个索引的信息

  1. @Test
  2. public void queryIndex() throws IOException {
  3. IndicesClient indices = client.indices();
  4. GetIndexRequest getIndexRequest = new GetIndexRequest("person");
  5. GetIndexResponse getIndexResponse = indices.get(getIndexRequest, RequestOptions.DEFAULT);
  6. Map<String, MappingMetaData> mappings = getIndexResponse.getMappings();
  7. mappings.forEach((k,v)->{
  8. System.out.println("key:"+k+",v:"+v.getSourceAsMap());
  9. });
  10. }

3.添加文档

  1. @Test
  2. public void addDoc() throws IOException {
  3. //数据对象
  4. Person p = new Person();
  5. p.setName("meiting");
  6. p.setAddress("sichuan");
  7. p.setAge(22);
  8. IndexRequest request = new IndexRequest("person").id("1").source(JSON.toJSONString(p),XContentType.JSON);
  9. IndexResponse index = client.index(request, RequestOptions.DEFAULT);
  10. }

4.修改文档

就跟添加文档一样,在es中如果指定文档的id存在就会就会更新这个文档。操作方式跟上面添加文档一样,不过需要指定文档的id。

5.查询操作

5.1根据id查询文档或者删除文档

  1. @Test
  2. public void findDocByID() throws IOException {
  3. GetRequest getIndexRequest = new GetRequest("person","1");
  4. GetResponse documentFields = client.get(getIndexRequest, RequestOptions.DEFAULT);
  5. System.out.println(documentFields.getSourceAsString());
  6. }
  7. //根据id删除文档
  8. @Test
  9. public void delDocByID() throws IOException {
  10. DeleteRequest deleteRequest = new DeleteRequest("person","1");
  11. DeleteResponse documentFields = client.delete(deleteRequest, RequestOptions.DEFAULT);
  12. System.out.println(documentFields.getId());
  13. }

5.2查询所有文档

  1. @Test
  2. public void findAllDoc() throws IOException {
  3. SearchRequest sr = new SearchRequest("person");
  4. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  5. sourceBuilder.from(0).size(20);//指定分页
  6. MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
  7. sourceBuilder.query(queryBuilder);
  8. sr.source(sourceBuilder);
  9. SearchResponse search = client.search(sr, RequestOptions.DEFAULT);
  10. System.out.println(search.getHits().getTotalHits()); //查询到的所有的文档数量
  11. SearchHits hits = search.getHits();
  12. hits.forEach(ele->{
  13. System.out.println(ele.getSourceAsString());
  14. });
  15. }

5.3term查询(词条查询) text支持分词,keyword不支持分词

  1. @Test
  2. public void termQuery() throws IOException {
  3. SearchRequest requst = new SearchRequest("person");
  4. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  5. QueryBuilder queryBuilder = QueryBuilders.termQuery("name","阿");
  6. sourceBuilder.query(queryBuilder);
  7. requst.source(sourceBuilder);
  8. SearchResponse search = client.search(requst, RequestOptions.DEFAULT);
  9. SearchHit[] hits = search.getHits().getHits();
  10. for (SearchHit hit : hits) {
  11. System.out.println(hit.getSourceAsString());
  12. }
  13. }
  14. /** 类似于
  15. get person/_search
  16. {
  17. "query":{
  18. "term":{
  19. "name":{
  20. "value":"阿"
  21. }
  22. }
  23. }
  24. }
  25. */

5.4match查询

  1. @Test
  2. public void matchQuery() throws IOException {
  3. SearchRequest requst = new SearchRequest("person");
  4. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  5. MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name", "老板");
  6. queryBuilder.operator(Operator.AND);//求并集
  7. sourceBuilder.query(queryBuilder);
  8. requst.source(sourceBuilder);
  9. SearchResponse search = client.search(requst, RequestOptions.DEFAULT);
  10. SearchHit[] hits = search.getHits().getHits();
  11. for (SearchHit hit : hits) {
  12. System.out.println(hit.getSourceAsString());
  13. }
  14. }
  15. /**类似于
  16. get person/_search
  17. {
  18. "query":{
  19. "match": {
  20. "name": {
  21. "query":"永恩",
  22. "operator": "and"
  23. }
  24. }
  25. }
  26. }
  27. */

5.5模糊查询

wildcard查询:会对查询条件进行分词。还可以使用通配符 ?(任意单个字符) *(0个或者多个字符)

regexp查询:正则查询

prefix查询:前缀查询

  1. @Test
  2. public void wildSearch() throws IOException {
  3. SearchRequest requst = new SearchRequest("person");
  4. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  5. QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("name","菲*");
  6. //QueryBuilder queryBuilder = QueryBuilders.regexpQuery("name","菲*"); //正则查询
  7. //QueryBuilder queryBuilder = QueryBuilders.prefixQuery("name","菲"); //前缀查询
  8. sourceBuilder.query(queryBuilder);
  9. requst.source(sourceBuilder);
  10. SearchResponse search = client.search(requst, RequestOptions.DEFAULT);
  11. SearchHit[] hits = search.getHits().getHits();
  12. for (SearchHit hit : hits) {
  13. System.out.println(hit.getSourceAsString());
  14. }
  15. }

5.6范围查询

range范围查询:查找指定字段在指定范围内包含值。查询年龄20到26的人并排序

  1. @Test
  2. public void rangeQuery() throws IOException {
  3. SearchRequest requst = new SearchRequest("person");
  4. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  5. QueryBuilder queryBuilder = QueryBuilders.rangeQuery("age").gte(20).lte(26);
  6. sourceBuilder.query(queryBuilder);
  7. sourceBuilder.sort("age", SortOrder.DESC); //排序
  8. requst.source(sourceBuilder);
  9. SearchResponse search = client.search(requst, RequestOptions.DEFAULT);
  10. SearchHit[] hits = search.getHits().getHits();
  11. for (SearchHit hit : hits) {
  12. System.out.println(hit.getSourceAsString());
  13. }
  14. }
  15. /**类似于
  16. get person/_search
  17. {
  18. "query":{
  19. "range": {
  20. "age": {
  21. "gte": 20,
  22. "lte": 24
  23. }
  24. }
  25. },
  26. "sort":[ //排序
  27. {
  28. "age":{
  29. "order":"desc"
  30. }
  31. }
  32. ]
  33. }
  34. */

5.7querySt ring查询

queryString查询就是:对查询条件进行分词,然后将分词后的查询条件和词条进行等值匹配。然后取并集。

这种查询的特点就是可以指定多个字段查询。比如下面就是查名字和地址中包含“老”的数据。

  1. @Test
  2. public void queryStringQuery() throws IOException {
  3. SearchRequest requst = new SearchRequest("person");
  4. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  5. QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("老").field("name").field("address").defaultOperator(Operator.OR);
  6. sourceBuilder.query(queryBuilder);
  7. sourceBuilder.sort("age", SortOrder.DESC); //排序
  8. requst.source(sourceBuilder);
  9. SearchResponse search = client.search(requst, RequestOptions.DEFAULT);
  10. SearchHit[] hits = search.getHits().getHits();
  11. for (SearchHit hit : hits) {
  12. System.out.println(hit.getSourceAsString());
  13. }
  14. }
  15. /**类似于
  16. get person/_search
  17. {
  18. "query":{
  19. "query_string": {
  20. "fields": ["name","address"],
  21. "query": "永恩 OR 瑟提"
  22. }
  23. }
  24. }
  25. */

        除了上面说的这些常用的查询操作外还包括许多其他的查询,比如说聚合查询、高亮查询等等。在官网都可以查到对应的例子。到时候可以去官网看对应的例子。

Spring Data 操作ES 

Spring Data也提供了操作ES数据库的功能,因为我们现在的项目基本都是基于Spring的,所以集成这个功能之后很多项目在考虑选择的时候也会把这种方式考了进来,我之前参与的项目就是采用的这种方式来操作ES数据库的。

1.搭建环境

添加依赖:添加依赖的时候要注意版本的选择,要选择对应的版本,参考官网Spring Data Elasticsearch - Reference Documentation

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.11</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springDataEs</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>springDataEs</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

然后第二步配置文件

spring.elasticsearch.rest.uris=127.0.0.1:9200 

前面要做的步骤就这两步。

2.实际操作

2.1创建实体以及接口 

  1. @Document(indexName = "animal",createIndex = true,shards = 1,replicas = 1)
  2. @Data
  3. public class Animal {
  4. @Id
  5. private long id;
  6. @Field(type= FieldType.Text)
  7. private String name;
  8. @Field(type=FieldType.Text)
  9. private String address;
  10. @Field(type = FieldType.Integer)
  11. private int age;
  12. }

这上面需要注意的就是几个注解:

  • @Document 注解作用在类上,说明这是一个文档对象。

        indexName:索引名称

        createIndex:是否需要创建索引,若为true就会自动创建索引

        shards、replicas:分片数量和副本数量

  • @Field(type= FieldType.Text)

    在es对应的这个字段的数据类型,这里FieldType.Tex在es创建后这个字段就对应为text类型的。

2.2创建存储库接口

创建了这个接口并继承ElasticsearchRepository之后,就可以使用了。

  1. public interface AnimalRepostory extends ElasticsearchRepository<Animal,Long> {
  2. }

继承关系:

然后就可以基本的使用了,步骤非常简单。。。

2.3新增文档 

我新写了一个接口,去尝试添加一个文档。

  1. @PostMapping("addDoc")
  2. public void addDoc(){
  3. Animal animal = new Animal();
  4. animal.setId(1);
  5. animal.setName("tew");
  6. animal.setAddress("111");
  7. animal.setAge(12);
  8. animalRepostory.save(animal);
  9. }

效果

可以看到,我们添加文档成功了,这个索引也自动给我们创建了。

Spring Data ElasticSearch对ES的操作进行了很完美的包装,他是基于Java High Level REST Client写的,使用起来非常方便。这里我就不对其他的方法进行讲解了,它的crud自己去搭建个环境跑起来,只要环境搭好之后后面就很方便了。对于简单的查询我们可以直接创建对应的接口方法就可以了。下面给出官网给出的例子:

  1. interface PersonRepository extends Repository<Person, Long> {
  2. List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
  3. // Enables the distinct flag for the query
  4. List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
  5. List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);
  6. // Enabling ignoring case for an individual property
  7. List<Person> findByLastnameIgnoreCase(String lastname);
  8. // Enabling ignoring case for all suitable properties
  9. List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);
  10. // Enabling static ORDER BY for a query
  11. List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
  12. List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
  13. }

分页查询和排序,只需要在定义接口方法的时候给出Pageable以及Sort规则就可以了。

例子:

  1. @PostMapping("findPage")
  2. public void findPage(){
  3. Pageable page = Pageable.ofSize(3).withPage(1);
  4. Iterable<Animal> all = animalRepostory.findAll(page);
  5. for(Iterator<Animal> iterator = all.iterator(); iterator.hasNext();System.out.println(iterator.next())){
  6. }
  7. }
  8. @PostMapping("findPageSort")
  9. public void findPageSort(){
  10. Sort sort = Sort.by("age").descending();
  11. Iterable<Animal> all = animalRepostory.findAll(sort);
  12. for(Iterator<Animal> iterator = all.iterator(); iterator.hasNext();System.out.println(iterator.next())){
  13. }
  14. }

自定义DSL查询:

这里用一个模糊查询举例:

在对应的接口创建一个接口,并在@Query注解里面写上对应的查询语句

  1. public interface AnimalRepostory extends ElasticsearchRepository<Animal,Long> {
  2. @Query("{\n" +
  3. " \"wildcard\": {\n" +
  4. " \"name\": {\n" +
  5. " \"value\": \"t*\"\n" +
  6. " }\n" +
  7. " }\n" +
  8. " }")
  9. List<Animal> findTest();
  10. }

效果:

  1. @PostMapping("findQuery")
  2. public void findQuery(){
  3. List<Animal> test = animalRepostory.findTest();
  4. test.forEach(ele->{
  5. System.out.println(ele);
  6. });
  7. }

Spring Data还提供了很多其他的查询功能,如果有需要用到的我建议可以去看看官网。 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/565868
推荐阅读
相关标签
  

闽ICP备14008679号