ES在Springboot中的基础使用

步骤一:引用相关类

 <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);
        }
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值