elasticSearch的使用

这里对于elasticSearch的下载安装和配置就不做详细的说明,具体说明下如何使用:

1.创建索引和删除索引
SpringBoot-data-elasticsearch提供了面向对象的方式操作elasticsearch
业务:创建一个商品对象,有这些属性:
id,title,category,brand,price,图片地址
在SpringDataElasticSearch中,只需要操作对象,就可以操作elasticsearch中的数据
Spring Data通过注解来声明字段的映射属性,有下面的三个注解:
@Document 作用在类,标记实体类为文档对象,一般有两个属性
indexName:对应索引库名称
type:对应在索引库中的类型
shards:分片数量,默认5
replicas:副本数量,默认1
@Id 作用在成员变量,标记一个字段作为id主键
@Field 作用在成员变量,标记为文档的字段,并指定字段映射属性:
type:字段类型,是枚举:FieldType,可以是text、long、short、date、integer、object等
text:存储数据时候,会自动分词,并生成索引
keyword:存储数据时候,不会分词建立索引
Numerical:数值类型,分两类
基本数据类型:long、interger、short、byte、double、float、half_float
浮点数的高精度类型:scaled_float
需要指定一个精度因子,比如10或100。elasticsearch会把真实值乘以这个因子后存储,取出时还原。
Date:日期类型
elasticsearch可以对日期格式化为字符串存储,但是建议我们存储为毫秒值,存储为long,节省空间。
index:是否索引,布尔类型,默认是true
store:是否存储,布尔类型,默认是false
analyzer:分词器名称,这里的ik_max_word即使用ik分词器

使用示例如下:

@Document(indexName = "item",type = "docs", shards = 5, replicas = 1)
public class Item {

    /**
     * @Id注解必须是springframework包下的org.springframework.data.annotation.Id
     */
    @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; // 图片地址
}

2.通用工具类
第三方的api提供了一个通用的工具类 ,可以用来创建和删除索引等一系列操作:ElasticsearchTemplate
esTemplate.createIndex();
esTemplate.delete
//推荐如下方式,根据类的名称和属性自动生成

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsDemoApplication.class)
public class EsDemoApplicationTests {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void testCreateIndex() {
        elasticsearchTemplate.createIndex(Item.class);
    }
}

同时提供了4.2.1. Repository接口
Spring Data 允许自动根据方法名或类的信息进行CRUD操作。只要定义接口,继承Repository提供的接口,就能具备各种基本的CRUD功能。

public interface ItemRepository extends ElasticsearchRepository<Item,Long>{
}

示例如下:新增功能

@Autowired
private ItemRepository itemRepository;

@Test
public void testSave(){
    Item item = new Item(1L, "小米9", " 手机",
            "小米", 2999.00, "http://image.baidu.com/13123.jpg");
    itemRepository.save(item);
}

2.查询,
//查询所有

@Test
public void query(){
    Iterable<Item> list = this.itemRepository.findAll(Sort.by("price").ascending());
    for (Item item : items) {
        System.out.println(item);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值