亲宝软件园·资讯

展开

集成spring data elasticsearch Springboot集成spring data elasticsearch过程详解

滚动的蛋 人气:0

版本对照

各版本的文档说明:https://docs.spring.io/spring-data/elasticsearch/docs/

1、在application.yml中添加配置

spring:
 data:
  elasticsearch:
   repositories:
    enabled: true
   #多实例集群扩展时需要配置以下两个参数
   #cluster-name: datab-search
   #cluster-nodes: 127.0.0.1:9300,127.0.0.1:9301  

  2、添加 Maven 依赖  

<!---开箱即用,版本默认和springboot版本对应-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  </dependency>

3、建立实体entity
注解说明:  

  Spring Data通过注解来声明字段的映射属性,有下面的三个注解:

  示例:

@Document(indexName = "cp_doc", type = "doc", shards = 10, replicas = 0)
public class CpDocument extends BaseEntity {
 
  @Id//作用在成员变量,标记一个字段作为id主键
  private long id ;
  @Field(type = FieldType.Text)
  private String name ;
  @Field(type = FieldType.Text)
  private String address ;
  public long getId() {
  return id;
  }
  public void setId(long id) {
  this.id = id;
  }
  public String getName() {
  return name;
  }
  public void setName(String name) {
  this.name = name;
  }
  public String getAddress() {
  return address;
  }
  public void setAddress(String address) {
  this.address = address;
}

 4、编写 Repository 访问层 

/**
 * 基本操作repository-curd
 * @author 滚动的蛋
 *
 */
public interface CpRepository extends ElasticsearchRepository<CpDocument, Integer> {
}

  5、创建索引+查询示例 

@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticSearchTest {
  @Autowired
   CpRepository cpRepository;
  @Autowired
  ElasticsearchTemplate elsTemplate;//ElasticsearchTemplate中提供了创建索引的API<br data-filtered="filtered"><br data-filtered="filtered">
  @Test
  public void addIndexTest() {
    //创建索引
    boolean indexRes = elsTemplate.createIndex(CpDocument.class);
    System.out.println("======创建索引结果:"+indexRes+"=========");
    //添加索引
    CpDocument cpTest = new CpDocument();
    cpTest.setId(1);
    cpTest.setName("阿里巴巴");
    cpTest.setAddress("北京路12号");
    cpRepository.save(cpTest);
  }
   
  @Test
  public void srarchTest() {
    //这个只做一个多字段的匹配查询示例,其它的可以查看API文档使用
    //"name","address" 为匹配的字段
     MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery("阿里巴巴","address","name");//多字段匹配QueryBuilder
     SearchQuery searchQuery = new NativeSearchQueryBuilder()//构建查询对象
         .withQuery(multiMatchQuery)
         .withIndices("cp_doc")//索引名
         .withPageable(PageRequest.of(0, 10))//分页
         .build();
     Iterable<CpDocument> productDtos = cpRepository.search(searchQuery);
     ArrayList<CpDocument> CpDocuments = Lists.newArrayList(productDtos);
     for (CpDocument cpDocument : CpDocuments) {
      System.out.printf("企业名称:%s,企业地址:%s\n",cpDocument.getName(),cpDocument.getAddress());
    }
  }

加载全部内容

相关教程
猜你喜欢
用户评论