1、导入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2、配置yml
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 192.168.232.110:9300
3、实体类
@Data
@Document( indexName = "heima3",type = "item", shards = 1, replicas = 0)
@NoArgsConstructor
@AllArgsConstructor
public class Item {
@Id
@Field(type = FieldType.Long)
Long id;
@Field(type = FieldType.Text,analyzer = "ik_smart")
String title; //标题
@Field(type = FieldType.Keyword)
String category;// 分类
@Field(type = FieldType.Keyword)
String brand; // 品牌
@Field(type = FieldType.Double)
Double price; // 价格
@Field(type = FieldType.Keyword,index = false)
String images; // 图片地址
}
4、创建ItemRepository接口
public interface ItemRepository extends ElasticsearchRepository<Item,Long> {}
5、客户端测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsTest {
@Autowired
ElasticsearchTemplate template;
@Autowired
private ItemRepository itemRepository;
//创建索引库,添加映射
@Test
public void testCreate(){
template.createIndex(Item.class);
template.putMapping(Item.class);
}
//添加数据
@Test
public void insertIndex(){
List<Item> list = new ArrayList<>();
list.add(new Item(2L, "坚果手机R1", " 手机", "锤子", 3699.00,"http://image.leyou.com/123.jpg"));
list.add(new Item(3L, "华为META10", " 手机", "华为", 4499.00, "http://image.leyou.com/3.jpg"));
// 接收对象集合,实现批量新增
itemRepository.saveAll(list);
}
//查找全部
@Test
public void testFind(){
Iterable<Item> items = itemRepository.findAll();
for (Item item : items) {
System.out.println(item);
}
}
如果想按照金额的区间来查询,这个时候需要在itemRepository另写一个方法,按照规定的命名来写方法名,spring自动会实现该方法
public interface ItemRepository extends ElasticsearchRepository<Item,Long> {
List<Item> findByPriceBetween(Double start, Double end);
}
@Test
public void testFindBy(){
Iterable<Item> items = itemRepository.findByPriceBetween(2000d,4000d);
for (Item item : items) {
System.out.println(item);
}
}