[Spring Boot Spring Boot] use of the Spring Data Elasticsearch integration elasticsearch

A, Spring Data Elasticsearch brief

  Spring Data Elasticsearch project will be the core of Spring concept to use Elasticsearch search engine development solutions. We provide a "template" as a high-level abstraction to store, query, sorting and classification of documents. You will notice Spring Framewor with the Spring data solr similarities and support mongodb

 GitHub Address: https://github.com/zhangboqing/spring-boot-demo-elasticsearch

Second, the integration steps

1) maven dependent

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

2) application.yml

spring:
  elasticsearch:
    rest:
      uris:
        - http://localhost:9200
      username: elastic
      password: 123456

3) the definition of an entity, an entity for an index

/**
 * @Author zhangboqing
 * @date 2019-12-06
 * / 
Public  interface EsConsts {

    /**
     * So use this type name index
     */
    String DEFAULT_TYPE_NAME = "_doc";

    /**
     * Index Name
     */
    String INDEX_NAME_MERCURY = "goods";

}
/**
 * @Author zhangboqing
 * @date 2019-12-06
 */
@Document(indexName = EsConsts.INDEX_NAME_MERCURY, type = EsConsts.DEFAULT_TYPE_NAME, shards = 1, replicas = 0)
@Data
@AllArgsConstructor
@NoArgsConstructor
public  class GoodsESEntity {
     // filter criteria including: product name, brand, size, suitable models, product number, the original number

    /**
     * Primary key, the product ID
     */
    @Id
    private Long goodsId;

    /**
     * product name
     */
    @Field(type = FieldType.Keyword)
    private String goodsName;
    /**
     * Brand
     */
    @Field(type = FieldType.Keyword)
    private String goodBrand;
    /**
     * Specifications
     */
    @Field(type = FieldType.Keyword)
    private String goodsSpec;
    /**
     * Product Number
     */
    @Field(type = FieldType.Keyword)
    private String goodsAccessoriesCode;
    /**
     * Original number
     */
    @Field(type = FieldType.Keyword)
    private String goodsOriginalFactoryCode;

    /**
     * Complex field, the word will be stored
     */
    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String groupData;
}

4) define Repository

/**
 * @Author zhangboqing
 * @date 2019-12-06
 */
public interface GoodsESRepository extends ElasticsearchRepository<GoodsESEntity, Long> {

    /**
     * According to goodsId range query
     */
    List<GoodsESEntity> findByGoodsIdBetween(Integer min, Integer max);

}

 

Third, the test

/**
 * @Author zhangboqing
 * @Date 2020-01-03
 */
@SpringBootTest
@ Slf4j
public class GoodsESRepositoryTest {

    @Autowired
    private GoodsESRepository goodsESRepository;

    /**
     * Testing New
     */
    @Test
    public void save() {
        GoodsESEntity goodsESEntity1 = new new GoodsESEntity ( 2L , " taillight L Volkswagen Jetta " , " international brand " , " 16D 945 095 " , " 31,231,231 " , " 16D 945 095 " ,
                 " taillight L Volkswagen Jetta international brands 16D 945 095 31231231 16D 945 095 " );
        GoodsESEntity2 GoodsESEntity = new new GoodsESEntity ( 1L , " after " , " international brand " , " 16D 945 095 " , " 31,231,231 " , " 16D 945 095 " ,
                 " The international brand 945 095 31,231,231 16D 945 16D 095 " );
        Iterable<GoodsESEntity> goodsESEntities = goodsESRepository.saveAll(Arrays.asList(goodsESEntity1, goodsESEntity2));
        log.info("【save】= {}", goodsESEntities);
    }


    /**
     * Testing Update
     */
    @Test
    public void update() {
        goodsESRepository.findById(1L).ifPresent(goodsESEntity -> {
            goodsESEntity.setGoodsName (goodsESEntity.getGoodsName () + " \ n-update update update update update " );
            GoodsESEntity save = goodsESRepository.save(goodsESEntity);
            log.info("【save】= {}", save);
        });
    }

    /**
     * Delete test
     */
    @Test
    public  void Delete () {
         // remove the primary key 
        goodsESRepository.deleteById ( 1L );

        // 对象删除
        goodsESRepository.findById(2L).ifPresent(goodsESEntity -> goodsESRepository.delete(goodsESEntity));

        // bulk delete 
        goodsESRepository.deleteAll (goodsESRepository.findAll ());
    }

    /**
     * Test normal query, press goodsId reverse
     */
    @Test
    public  void  select () {
        goodsESRepository.findAll(Sort.by(Sort.Direction.DESC, "goodsId"))
                .forEach(goodsESEntity -> log.info("【goods】: {}", JSON.toJSONString(goodsESEntity)));
    }

    /**
     * Custom queries, range queries based on goodsId
     */
    @Test
    public void customSelectRangeOfAge() {
        goodsESRepository.findByGoodsIdBetween(1, 2).forEach(goodsESEntity -> log.info("【goods】: {}", JSON.toJSONString(goodsESEntity)));
    }

    /**
     * Advanced Search
     */
    @Test
    public  void advanceSelect () {
         // QueryBuilders provides many static methods that can achieve most of the query package 
        MatchQueryBuilder QueryBuilder = QueryBuilders.matchQuery ( " goodsName " , " Porsche V20 " );
        log.info("【queryBuilder】= {}", queryBuilder.toString());

        goodsESRepository.search(queryBuilder).forEach(goodsESEntity -> log.info("【goods】: {}", JSON.toJSONString(goodsESEntity)));
    }

    /**
     * Custom Advanced Search
     */
    @Test
    public  void customAdvanceSelect () {
         // configured query 
        NativeSearchQueryBuilder QueryBuilder = new new NativeSearchQueryBuilder ();
         // add basic conditions word 
        queryBuilder.withQuery (QueryBuilders.matchQuery ( " goodsName " , " Porsche V20 " ));
         // Sort 
        queryBuilder.withSort (SortBuilders.fieldSort ( " goodsId " ) .order (SortOrder.DESC));
         // tab conditions 
        queryBuilder.withPageable (PageRequest.of ( 0 , 2 ));
        Page<GoodsESEntity> goodsESEntities = goodsESRepository.search(queryBuilder.build());
        log.info ( " [] The total number of people {} = " , goodsESEntities.getTotalElements ());
        log.info("【people】总页数 = {}", goodsESEntities.getTotalPages());
        goodsESEntities.forEach(goodsESEntity -> log.info("【goods】= {}",JSON.toJSONString(goodsESEntity)));
    }

    /**
     * Test polymerization Test average goodsId
     */
    @Test
    public  void AVG () {
         // configured query 
        NativeSearchQueryBuilder QueryBuilder = new new NativeSearchQueryBuilder ();
         // do not result in any query 
        queryBuilder.withSourceFilter ( new new FetchSourceFilter ( new new String [] { "" }, null ));

        // 平均goodsId
        queryBuilder.addAggregation(AggregationBuilders.avg("goodsIdAvg").field("goodsId"));

        log.info("【queryBuilder】= {}", JSON.toJSONString(queryBuilder.build()));

        AggregatedPage<GoodsESEntity> goodsESEntities = (AggregatedPage<GoodsESEntity>) goodsESRepository.search(queryBuilder.build());
        double avgGoodsId = ((InternalAvg) goodsESEntities.getAggregation("goodsIdAvg")).getValue();
        log.info("【avgGoodsId】= {}", avgGoodsId);
    }

    /**
     * Senior aggregate query test
     */
    @Test
    public  void advanceAgg () {
         // configured query 
        NativeSearchQueryBuilder QueryBuilder = new new NativeSearchQueryBuilder ();
         // do not result in any query 
        queryBuilder.withSourceFilter ( new new FetchSourceFilter ( new new String [] { "" }, null ));

        // 1. Add a new polymerization, Terms type, name goodsName polymerization, the polymerization field is goodsId 
        queryBuilder.addAggregation (AggregationBuilders.terms ( " goodsName " ) .field ( " goodsName " )
                 // 2. In the polymerization goodsName barrel nested polymerization averaging goodsId 
                .subAggregation (AggregationBuilders.avg ( " goodsIdAvg " ) .field ( " goodsId " )));

        log.info("【queryBuilder】= {}", JSON.toJSONString(queryBuilder.build()));

        // 3. 查询
        AggregatedPage<GoodsESEntity> people = (AggregatedPage<GoodsESEntity>) goodsESRepository.search(queryBuilder.build());

        // 4. Analytical
         // 4.1. Withdrawn from the polymerization goodsName called results, as is the use of type String fields term polymerization carried out, the results turned StringTerm stronger type 
        StringTerms goodsName = (StringTerms) people.getAggregation ( " goodsName " );
         // 4.2 acquiring the tub. 
        List <StringTerms.Bucket> = buckets goodsName.getBuckets ();
         for (StringTerms.Bucket bucket: buckets) {
             // . 4.3 tub acquired key, i.e. 4.4 goodsName name acquired. the number of documents in the tub 
            log.info ( " {} {} a total " , bucket.getKeyAsString (), bucket.getDocCount ());
             // . 4.5 of 5 acquisition sub polymerization results:
            InternalAvg avg = (InternalAvg) bucket.getAggregations().asMap().get("goodsIdAvg");
            log.info("平均goodsId:{}", avg);
        }
    }

}

 

Guess you like

Origin www.cnblogs.com/756623607-zhang/p/12147410.html