您当前的位置: 首页 >  $驽马十驾$ ar

Springboot整合Elasticsearch

$驽马十驾$ 发布时间:2022-04-28 10:45:17 ,浏览量:2

Springboot整合Elasticsearch
  • 新建Springboot项目
  • xml文件添加依赖
  • 添加配置
  • 新建配置类
  • 创建实体类
  • Dao层代码
  • 测试代码
  • 自定义查询

新建Springboot项目

此步骤不再赘述

xml文件添加依赖

第一步当然是添加依赖了,本次测试主要使用了以下三个依赖:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.7
         
    
    com.wpp
    springdata_es
    0.0.1-SNAPSHOT
    springdata_es
    Demo project for Spring Boot
    
        1.8
    
    

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.projectlombok
            lombok
        

        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



添加配置

第二步自然是在yml配置文件中添加elasticsearch的信息,如下:

# es 服务地址
elasticsearch:
  host: localhost
# es 服务端口
  port: 9200
新建配置类

第三步,涉及到Springboot整合的往往离不开配置类,如下配置,在启动项目的时候就实例化了elasticsearch的客户端:

package com.wpp.springdata_es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

/**
 * @Author wpp
 * @Date 2022/04/27/10:30
 * @Description
 */
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
    //对应yml文件中的配置
    private String host;
    private Integer port;
    @Override
    public RestHighLevelClient elasticsearchClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
        RestHighLevelClient restHighLevelClient = new
                RestHighLevelClient(builder);
        return restHighLevelClient;
    }
}

创建实体类

第四步,下面就是我们要操作的实体类了,类似于MyBatis-Plus,针对elasticsearch也有自己的注解:

package com.wpp.springdata_es.esentity;

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;

/**
 * @Author wpp
 * @Date 2022/04/27/10:35
 * @Description
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "product",shards = 2,replicas = 1)
public class Product {
    //必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id"
    @Id
    private Long id;//商品唯一ID
    /**
     * type:字段数据类型
     * index:是否索引(默认:true)
     * Keyword:短语,不进行分词
     */
    @Field(type = FieldType.Text)
    private String title;//商品名称

    @Field(type = FieldType.Keyword)
    private String category;//分类名称

    @Field(type = FieldType.Double)
    private Double price;//商品价格

    @Field(type = FieldType.Keyword,index = false)
    private String images;//图片地址
}

Dao层代码

同样类似于Mybatis-Plus,我们也有自己的interface,并且继承于ElasticsearchRepository,这样就像MyBatis-Plus一样已经提供了很多的用于操作的Api。

package com.wpp.springdata_es.dao;


import com.wpp.springdata_es.esentity.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 * @Author wpp
 * @Date 2022/04/27/10:33
 * @Description
 */
public interface ProductDao extends ElasticsearchRepository {
}

测试代码

接下来操作对象就是操作索引了。

package com.wpp.springdata_es;

import com.wpp.springdata_es.dao.ProductDao;
import com.wpp.springdata_es.esentity.Product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

@SpringBootTest
class SpringdataEsApplicationTests {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private ProductDao productDao;

    //创建索引
    @Test
    void createIndex() {
        //创建索引,系统初始化会自动创建索引
        System.out.println("创建索引");
    }

    //删除索引
    @Test
    void deleteIndex() {
        boolean delete = elasticsearchRestTemplate.indexOps(Product.class).delete();
        System.out.println("删除索引:" + delete);
    }

    //新增文档
    @Test
    void save() {
        Product product = new Product();
        product.setId(1L);
        product.setTitle("华为笔记本");
        product.setCategory("电脑");
        product.setPrice(3980.0);
        product.setImages("http://www.baidu/hw.jpg");
        Product save = productDao.save(product);
    }
	
}

自定义查询

ElasticsearchRepository虽然为我们提供了一些方法,但是我们依然可以根据约定进行自定义方法 例如:

package com.wpp.springdata_es.dao;


import com.wpp.springdata_es.esentity.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

/**
 * @Author wpp
 * @Date 2022/04/27/10:33
 * @Description
 */
public interface ProductDao extends ElasticsearchRepository {

    //自定义查询
    List findByPriceBetweenOrderByPrice(double price1, double price2);
}

测试代码如下:

	//自定义 查询
    @Test
    public void test(){
        List products = productDao.findByPriceBetweenOrderByPrice(2000, 2005);
        for (Product product1 : products) {
            System.out.println(product1);
        }

    }

更多的自定义方法命名约定

KeywordSampleElasticsearch Query StringAndfindByNameAndPrice{“bool” : {“must” : [ {“field” : {“name” : “?”}}, {“field” : {“price” : “?”}} ]}}OrfindByNameOrPrice{“bool” : {“should” : [ {“field” : {“name” : “?”}}, {“field” : {“price” : “?”}} ]}}IsfindByName{“bool” : {“must” : {“field” : {“name” : “?”}}}}NotfindByNameNot{“bool” : {“must_not” : {“field” : {“name” : “?”}}}}BetweenfindByPriceBetween{“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : ?,“include_lower” : true,“include_upper” : true}}}}}LessThanEqualfindByPriceLessThan{“bool” : {“must” : {“range” : {“price” : {“from” : null,“to” : ?,“include_lower” : true,“include_upper” : true}}}}}GreaterThanEqualfindByPriceGreaterThan{“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : null,“include_lower” : true,“include_upper” : true}}}}}BeforefindByPriceBefore{“bool” : {“must” : {“range” : {“price” : {“from” : null,“to” : ?,“include_lower” : true,“include_upper” : true}}}}}AfterfindByPriceAfter{“bool” : {“must” : {“range” : {“price” : {“from” : ?,“to” : null,“include_lower” : true,“include_upper” : true}}}}}LikefindByNameLike{“bool” : {“must” : {“field” : {“name” : {“query” : “?*”,“analyze_wildcard” : true}}}}}StartingWithfindByNameStartingWith{“bool” : {“must” : {“field” : {“name” : {“query” : “?*”,“analyze_wildcard” : true}}}}}EndingWithfindByNameEndingWith{“bool” : {“must” : {“field” : {“name” : {“query” : “*?”,“analyze_wildcard” : true}}}}}Contains/ContainingfindByNameContaining{“bool” : {“must” : {“field” : {“name” : {“query” : “?”,“analyze_wildcard” : true}}}}}InfindByNameIn(Collectionnames){“bool” : {“must” : {“bool” : {“should” : [ {“field” : {“name” : “?”}}, {“field” : {“name” : “?”}} ]}}}}NotInfindByNameNotIn(Collectionnames){“bool” : {“must_not” : {“bool” : {“should” : {“field” : {“name” : “?”}}}}}}NearfindByStoreNearNot Supported Yet !TruefindByAvailableTrue{“bool” : {“must” : {“field” : {“available” : true}}}}FalsefindByAvailableFalse{“bool” : {“must” : {“field” : {“available” : false}}}}OrderByfindByAvailableTrueOrderByNameDesc{“sort” : [{ “name” : {“order” : “desc”} }],“bool” : {“must” : {“field” : {“available” : true}}}}
关注
打赏
1688896170
查看更多评论

$驽马十驾$

暂无认证

  • 2浏览

    0关注

    29博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0510s