SpringBoot整合Elasticsearch

2021-06-08 15:03

阅读:385

标签:应用   _id   auto   retention   use   表达   com   put   host   

说明

相关环境:

SpringBoot - 2.4.3

Elasticsearch - 7.11.2

这个例子默认已搭建好springboot、jdbc、mybatis和Swagger(非必需)

添加依赖


org.springframework.boot
    spring-boot-starter-data-elasticsearch

配置类

/**
 * es客户端配置类
 * 需要继承抽象类AbstractElasticsearchConfiguration,重写方法中配置ip和端口
 * @author
 */
@Configuration
public class EsClientConfig extends AbstractElasticsearchConfiguration {
    private final String HOST_AND_PORT = "192.168.xx.xxx:9200";

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
            	// ip和端口号
                .connectedTo(HOST_AND_PORT)
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

实现代码

大概结构:

  • 语言类
  • 细分为计算机语言类,包含Java、C++、JavaScript
{
    "list": [
        {
            "id": 1,
            "name": "Computer Language",
            "description": "计算机语言",
            "type": 1,
            "containList": [
                {
                    "id": 1,
                    "type:": 1,
                    "value": "Java",
                    "name": "Java"
                },
                {
                    "id": 2,
                    "type:": 1,
                    "value": "C++",
                    "name": "C艹"
                }
            ]
        },
        {
            "id": 2,
            "name": "Person Language",
            "description": "人类语言",
            "type": 2,
            "containList": [
                {
                    "id": 1,
                    "type:": 2,
                    "value": "zh-CN",
                    "name": "汉语"
                },
                {
                    "id": 2,
                    "type:": 2,
                    "value": "en",
                    "name": "??语"
                }
            ]
        }
    ]
}

类文件

  • Language
/**
 * 语言类
 * @author
 */
@Data
@Document(indexName = "language", shards = 1, replicas = 0)
public class Language {
    @Id
    private int id;
    private int type;
    @Field(type = FieldType.Keyword)
    private String name;
    @Field(type = FieldType.Keyword)
    private String description;
    @Field(type = FieldType.Nested)
    private List languageDetailsList;
}
  • LanguageDetails
/**
 * 计算机语言
 * @author
 */
@Data
public class LanguageDetails {
    @Id
    private int id;
    private int type;
    @Field(type = FieldType.Keyword)
    private String value;
    @Field(type = FieldType.Keyword)
    private String name;
}

es操作接口

对es的操作经由这个接口完成,接口必须继承ElasticsearchRepository,继承这个接口不需要实现类,就可以使用es的操作方法。

/**
 * ES操作接口
 * @author
 */
public interface EsReponsitory extends ElasticsearchRepository {}

mapper接口

/**
 * ES mapper接口
 * @author
 */
@Mapper
public interface EsMapper {
    /**
     * 获取语言数据
     * @param id
     * @return
     */
    List getAllLanguages(@Param("id") Long id);
}

mapper.xml:LanguageMapper.xml

esService接口

/**
 * es操作Service接口
 * @author
 */
@Component
public interface EsService {
    /**
     * 从数据库中导入所有商品到ES
     * @return
     */
    int importAll();

    /**
     * 根据id删除商品
     * @param id
     */
    void delete(int id);
}

esServiceImpl接口实现类

/**
 * es操作实现类
 * @author
 */
@Service
public class EsServiceImpl implements EsService {
    @Resource
    private EsMapper esMapper;
    @Resource
    private EsReponsitory esReponsitory;

    @Override
    public int importAll() {
        try {
            // 将对象数据从数据库中取出来
            List languageList = esMapper.getAllLanguages(null);
            // 将对象集合通过ElasticsearchRepository存入到es中
            esReponsitory.saveAll(languageList);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return 0;
        }
        return 1;
    }

    @Override
    public void delete(int id) {
        esReponsitory.deleteById(id);
    }
}

Controller调用接口

/**
 * @author
 */
@Api(tags = "es接口测试")
@RestController
@RequestMapping("/es")
public class EsController {

    @Resource
    private EsService esService;

    @ApiOperation("从数据库中导入全部数据")
    @PostMapping(value = "/importAll")
    public int importFromDb() {
        return esService.importAll();
    }

    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    public void deleteById(@PathVariable("id") int id) {
        esService.delete(id);
    }
}

查询结果

Kibana的devTool中使用命令查询结果或在浏览器中调用接口

GET /language/_search # 命令行
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "language",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "_class" : "dev.springboot.elasticsearch.Language",
          "id" : 1,
          "type" : 1,
          "name" : "Computer",
          "description" : "计算机语言",
          "languageDetailsList" : [
            {
              "id" : 1,
              "type" : 1,
              "value" : "Java",
              "name" : "Java"
            },
            {
              "id" : 2,
              "type" : 1,
              "value" : "C++",
              "name" : "C艹"
            }
          ]
        }
      },
      {
        "_index" : "language",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "_class" : "dev.springboot.elasticsearch.Language",
          "id" : 2,
          "type" : 2,
          "name" : "Person",
          "description" : "人类语言",
          "languageDetailsList" : [
            {
              "id" : 3,
              "type" : 2,
              "value" : "zh-CN",
              "name" : "中文"
            },
            {
              "id" : 4,
              "type" : 2,
              "value" : "en",
              "name" : """??语"""
            }
          ]
        }
      }
    ]
  }
}

需要关注的点

实体类注解说明

  • @Document
@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Document {
    // 用于存储此实体的索引的名称。它可以包含SpEL模板表达式,例如"log-#{T(java.time.LocalDate).now().toString()}" 
    // 简单说就是es中的index, 即:GET /index/_search
    String indexName();

    boolean useServerConfiguration() default false;
	// 索引分片数
    short shards() default 1;
	// 索引副本数
    short replicas() default 1;
	// 索引的刷新间隔。用于索引创建。默认值为“ 1s”
    String refreshInterval() default "1s";
	// 索引的索引存储类型。用于索引创建。默认值为“ fs”
    String indexStoreType() default "fs";
	// 标记是否在存储库引导中创建索引。默认值是true
    boolean createIndex() default true;
	// 版本管理的配置。默认值为EXTERNAL
    VersionType versionType() default VersionType.EXTERNAL;
}
  • @Id:在字段级别应用,以标记用于标识目的的字段

  • @Field

public @interface Field {
	// 字段名称,它将在Elasticsearch文档中表示,如果未设置,则使用Java字段名称
    @AliasFor("value")
    String name() default "";
	// 字段类型,如:Text, Keyword, Long, Integer, Short, Byte等
    FieldType type() default FieldType.Auto;
	// 记原始字段值是否应存储在Elasticsearch中,默认值为false
    boolean store() default false;
    // 其他属性省略
}

ElasticsearchRepository接口原理说明

  • 底层Repository接口

    根据Spring Data官方文档:

    Spring Data存储库抽象的中央接口 Repository,该接口主要用作标记接口,以捕获要使用的类型并发现扩展该接口的接口

    @Indexed
    public interface Repository {}
    
  • CrudRepository接口

    继承自中央接口Repository,作用是为正在管理的实体类提供复杂的CRUD功能

    @NoRepositoryBean
    public interface CrudRepository extends Repository {
         S save(S var1);
    
         Iterable saveAll(Iterable var1);
    
        Optional findById(ID var1);
    
        boolean existsById(ID var1);
    
        Iterable findAll();
    
        Iterable findAllById(Iterable var1);
    
        long count();
    
        void deleteById(ID var1);
    
        void delete(T var1);
    
        void deleteAll(Iterable extends T> var1);
    
        void deleteAll();
    }
    
  • PagingAndSortingRepository接口

    继承自CrudRepository接口,添加了其他方法来简化对实体的分页访问

    @NoRepositoryBean
    public interface PagingAndSortingRepository extends CrudRepository {
        Iterable findAll(Sort var1);
    
        Page findAll(Pageable var1);
    }
    
  • ElasticsearchRepository接口

    继承自PagingAndSortingRepository接口,是由elasticsearch提供具体的方法,其实现类是

    public class SimpleElasticsearchRepository implements ElasticsearchRepository {
        // 本次用到的saveAll方法,
        public  Iterable saveAll(Iterable entities) {
            Assert.notNull(entities, "Cannot insert ‘null‘ as a List.");
            IndexCoordinates indexCoordinates = this.getIndexCoordinates();
            this.executeAndRefresh((operations) -> {
                return operations.save(entities, indexCoordinates);
            });
            return entities;
        }
    }
    

所以,直接继承这个接口,不需要实现类即可使用es提供的基本方法

SpringBoot整合Elasticsearch

标签:应用   _id   auto   retention   use   表达   com   put   host   

原文地址:https://www.cnblogs.com/chengshuai5421/p/14525924.html


评论


亲,登录后才可以留言!