SpringBoot整合Spring Data Elasticsearch

2.0.6.RELEASE

UTF-8

UTF-8

1.8

org.springframework.boot

spring-boot-starter-data-elasticsearch

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-maven-plugin

目录结构:

SpringBoot整合Spring Data Elasticsearch_第1张图片

application.yml文件配置:

spring:

data:

elasticsearch:

cluster-name: elasticsearch

cluster-nodes: 192.168.42.136:9300

创建启动器:

@SpringBootApplication

public class ElasticsearchApplication {

public static void main(String[]args){

SpringApplication.run(ElasticsearchApplication.class);

}

}

创建实体类:

public class Item {

Long id;

String title; //标题

String category;// 分类

String brand; // 品牌

Double price; // 价格

String images; // 图片地址

/**

  • GET、SET、toString

*/

}

添加映射信息:

Spring Data通过注解来声明字段的映射属性,有下面的三个注解:

  • @Document 作用在类,标记实体类为文档对象,一般有四个属性

  • indexName:对应索引库名称

  • type:对应在索引库中的类型

  • shards:分片数量,默认5

  • replicas:副本数量,默认1

  • @Id 作用在成员变量,标记一个字段作为id主键

  • @Field 作用在成员变量,标记为文档的字段,并指定字段映射属性:

  • type:字段类型,取值是枚举:FieldType

  • index:是否索引,布尔类型,默认是true

  • store:是否存储,布尔类型,默认是false

  • analyzer:分词器名称:ik_max_word

@Document(indexName = “item”,type = “docs”, shards = 1, replicas = 0)

public class Item {

@Id

private Long id;

@Field(type = FieldType.Text, analyzer = “ik_max_word”)

private String title; //标题

@Field(type = FieldType.Keyword)

private String category;// 分类

@Field(type = FieldType.Keyword)

private String brand; // 品牌

@Field(type = FieldType.Double)

private Double price; // 价格

@Field(index = false, type = FieldType.Keyword)

private String images; // 图片地址

public Item(){}

public Item(Long id, String title, String category, String brand, Double price, String images) {

this.id = id;

this.title = title;

this.category = category;

this.brand = brand;

this.price = price;

this.images = images;

}

}

Template索引操作


新建一个测试类:ElasticsearchTest,注意需要与启动器在同一目录结构下

@SpringBootTest

@RunWith(SpringRunner.class)

public class ElasticsearchTest {

}

创建索引和映射: ElasticsearchTemplate中提供了创建

你可能感兴趣的:(spring,spring,boot,elasticsearch)