步骤一:引用相关类
<parent>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
</parent>
<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-test</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
步骤二:配置yml
spring:
elasticsearch:
rest:
uris: http://localhost:9200
步骤三:创建一个doc基础类
order是表示的索引库名,type是文档类型
@Document(indexName = "order",type = "_doc")
@Data
public class OrderDoc {
@Id
private Long id;
//分词用Text
@Field(type = FieldType.Text,analyzer = "ik_smart",searchAnalyzer ="ik_smart")
private String title;
//不分词用keyword
@Field(type = FieldType.Keyword)
private String brand;
@Field(type = FieldType.Integer)
private int count;
@Field(type = FieldType.Integer)
private int status;
}
步骤四:创建一个OrderESRepository接口
public interface OrderESRepository extends ElasticsearchRepository<OrderDoc,Long> {
}
继承ElasticsearchRepository<>中的泛型要根据创建的doc文档类变化
步骤五:开启启动类
@SpringBootApplication
public class ESApplication {
public static void main(String[] args) {
SpringApplication.run(ESApplication.class, args);
}
}
步骤六:编写测试类测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ESApplication.class)
public class OrderESTest {
@Autowired
private ElasticsearchRestTemplate template;
@Autowired
private OrderESRepository esRepository;
@Test
public void test() {
//创建索引
template.createIndex(OrderDoc.class);
//创建映射
template.putMapping(OrderDoc.class);
}
@Test
public void testAdd() {
for (long i=1; i < 10; i++) {
OrderDoc orderDoc = new OrderDoc();
orderDoc.setId(i);
orderDoc.setBrand("阿迪达斯");
orderDoc.setCount(10);
orderDoc.setTitle("爱坤");
orderDoc.setStatus(1);
esRepository.save(orderDoc);
}
}
}