启动Elasticsearch的集群,如果不会搭建集群可以看我以前的文章

         进入到head的扩展应用,连接后面的健康值为green就表示集群没问题

 

Spring Data Elasticsearch  

特征:    Spring配置支持使用基于Java的 @Configuration 类或ES客户端实例的XML命名空间。
            ElasticsearchTemplate 帮助类,它可以提高执行常见ES操作的效率。包括文档和POJO之间的集成对象映射。
            与Spring的转换服务集成的功能丰富的对象映射。
            基于注释的映射元数据,但可扩展以支持其他元数据格式。
            自动实现 Repository 接口,包括对自定义查找器方法的支持
            对存储库的CDI支持

        1.导入pom的依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

        2.配置核心配置文件

# 集群的名称
spring.data.elasticsearch.cluster-name=xm
# 集群的ES服务器Node节点信息
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303

        注意:如果配置文件报红是因为springboot版本太高不兼容,需要调低版本                                      建议调为 <version>2.1.16.RELEASE</version>,在低版本中,没有总的运行测试类,需要将测试类注解的包重新导一下, import org.junit.Test;

        注解: 

            @Document
                indexName:索引库名称          type:类型名称,默认是"docs"
                shards:分⽚数量,默认5        replicas:副本数量,默认1
            @Id          声明实体类的id
            @Field         type:字段的数据类型             analyzer:指定分词器类型
                                index:是否创建索引

        3.创建实体类Producter

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; 
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
@Document(indexName = "leq",type = "product",shards = 3,replicas = 1)
public class Producter {
    @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(type = FieldType.Keyword,index = false)
    private String images; // 图片地址
}

        4.测试集群有没有连通

import com.esclient.es.pojo.Producter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)//低版本的单元测试添加的注解
@SpringBootTest
public class SpringDataESTests {
    @Autowired
    private ElasticsearchTemplate template; 

    @Test
    public void check(){
        System.out.println(template);
    } 
}

 控制台打印org.springframework.data.elasticsearch.core.ElasticsearchTemplate@6c6379c就表示连接成功

        创建索引,索引创建后可以在head插件中看到刚刚创建的索引,索引在实例类中定义的 

        加载映射

         创建mapper层,定义一个接口继承ElasticsearchRepository类,第一个参数为映射的实体类,第二个为主键id的类型

import com.esclient.es.pojo.Producter;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface ProducterRepository extends ElasticsearchRepository<Producter,Long> {

}

        新增,新增的数据可以在head插件中查看到 

 @Test//新增
    public void addDocument(){
        Producter producter = new Producter(1l, "荣耀", "手机", "小米", 2999d, "1.img");
        Producter save = producterRepository.save(producter);
        System.err.println(save);
    }

        批量新增

    @Test//批量新增
    public void batchAddDocument(){
        Producter p1 = new Producter(2l, "华为荣耀", "手机", "鸿蒙", 2999d, "1.img");
        Producter p2 = new Producter(3l, "小米荣耀", "手机", "黑米", 2899d, "1.img");
        Producter p3 = new Producter(4l, "王者荣耀", "手机", "白米", 2969d, "1.img");
        Producter p4 = new Producter(5l, "小满荣耀", "手机", "红米", 2109d, "1.img");

        List<Producter> l =new ArrayList<>();
       l.add(p1);
       l.add(p2);
       l.add(p3);
       l.add(p4);

       Iterable<Producter> producters = producterRepository.saveAll(l);
        System.err.println(producters.toString());
    }

 

        查询

        1.通过id查询

  @Test//通过id查询
    public void findById(){
        Optional<Producter> option = producterRepository.findById(1l);

        Producter defaultbean = new Producter();
        defaultbean.setTitle("这是一个默认的数据");

        Producter producter = option.orElse(defaultbean);//如果option为空把defaultbean返回给用户,不为空把查询出来的数据返回给用户
        System.err.println(producter);
    }

         2.查询所有

     @Test//查询所有
    public void findAll(){
        Iterable<Producter> all = producterRepository.findAll();
        all.forEach(System.err::println);
    }

        3.自定义方法查询 根据区间查询商品信息

        在mapper层定义方法 

   @Test//自定义方法查询  根据区间查询商品信息
    public void between(){
        List<Producter> byPriceBetween = producterRepository.findByPriceBetween(2900d, 3000d);
        byPriceBetween.forEach(System.err::println);
    }

                      关键字                                                         示例                                                         Elasticsearch查询字符串

                         And                                               findByNameAndPrice                         {"bool" : {"must" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}

                         Or                                                      findByNameOrPrice                            {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}

                        Is                                                         findByName                                                 {"bool" : {"must" : {"field" : {"name" : "?"}}}}

                         Not                                                   findByNameNot                                         {"bool" : {"must_not" : {"field" : {"name" : "?"}}}}

                 Betweend                                                 findByPriceBetween                 {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}

                 LessThanEqual                                         findByPriceLessThan             {"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}

                GreaterThanEqual                                 findByPriceGreaterThan            {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}

                Before                                                    findByPriceBefore                      {"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}

                 After                                                        findByPriceAfter                       {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}

                 Like                                                         findByNameLike                               {"bool" : {"must" : {"field" : {"name" : {"query" : "? *","analyze_wildcard" : true}}}}}

                StartingWith                                          findByNameStartingWith                     {"bool" : {"must" : {"field" : {"name" : {"query" : "? *","analyze_wildcard" : true}}}}}

                 EndingWith                                         findByNameEndingWith                        {"bool" : {"must" : {"field" : {"name" : {"query" : "*?","analyze_wildcard" : true}}}}}

                Contains/Containing                                 findByNameContaining                    {"bool" : {"must" : {"field" : {"name" : {"query" : "? ","analyze_wildcard" : true}}}}}

                 In                                                         findByNameIn(Collectionnames)          {"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}}

                 NotIn                                                 findByNameNotIn(Collectionnames)                 {"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}}

                 Near                                                 findByStoreNear                                               Not Supported Yet !

                 True                                                         findByAvailableTrue                                 {"bool" : {"must" : {"field" : {"available" : true}}}}

                False                                                         findByAvailableFalse                                {"bool" : {"must" : {"field" : {"available" : false}}}}

                OrderBy                                                findByAvailableTrueOrderByNameDesc        {"sort" : [{ "name" : {"order" : "desc"} }],"bool" : {"must" : {"field" : {"available" : true}}}}

Logo

欢迎加入我们的广州开发者社区,与优秀的开发者共同成长!

更多推荐