1、pom.xml导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
2、application.yml配置文件
server:
port: 8080
servlet:
context-path: /
spring:
application:
name: elasticsearch
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss.SSS
locale: zh_CN
serialization:
# 格式化输出
indent_output: false
elasticsearch:
uris: 127.0.0.1:9200
3、使用方式
3.1、@Repository注解
3.1.1、先创建对应实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;import org.springframework.data.elasticsearch.annotations.FieldType;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "shopping")
public class Shopping {
/**
* 必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id"
*/
@Id
private String id;
/**
* type : 字段数据类型
* analyzer : 分词器类型
* index : 是否索引(默认:true)
* Keyword : 短语,不进行分词
*/
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String title;
@Field(type = FieldType.Keyword)
private String category;
@Field(type = FieldType.Keyword, index = false)
private String images;
@Field(type = FieldType.Double)
private Double price;
}
3.1.2、再创建一个Repository处理接口
import com.lk.es.entity.Shopping;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ShoppingRepository extends ElasticsearchRepository<Shopping, String> {
}
3.1.3、最后就可以使用
@Autowired
private ShoppingRepository shoppingRepository;
// 添加
Shopping shopping = new Shopping();
shopping.setTitle("败家之眼");
shopping.setCategory("华硕");
shopping.setImages("http://www.gulixueyuan.com/xm.jpg");
shopping.setPrice(15999D);
shoppingDao.save(shopping);
// 修改
Shopping shopping = new Shopping();
shopping.setId("修改的数据ID");
shopping.setTitle("败家之眼");
shopping.setCategory("华硕");
shopping.setImages("http://www.gulixueyuan.com/xm.jpg");
shopping.setPrice(15999D);
shoppingRepository.save(shopping);
// 删除
Shopping shopping = new Shopping();
shopping.setId("删除的数据ID");
shoppingRepository.delete(shopping);
// 查询全部
Iterable<Shopping> all = shoppingRepository.findAll();
for (Shopping shopping : all) {
System.out.println(shopping.toString());
}
其他方法就不写了......
3.2、ElasticsearchRestTemplate
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
3.3、RestHighLevelClient
@Autowired
private RestHighLevelClient restHighLevelClient;