springboot data系列之elasticsearch入门

springboot data系列之elasticsearch入门

Scroll Down

spring-data-elasticsearch入门

Springboot使用elasticsearch

1.创建项目elasticsearch

2.添加依赖

 <parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.2.1.RELEASE</version>
</parent>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

3.创建实体类BookDO

@Data
@ToString
@Document(indexName = "book_index", shards = 1, replicas = 0)
public class BookDO {

    @Id
    private Long id;

    /**
     * text:存储数据时候,会自动分词,并生成索引
     * keyword:存储数据时候,不会分词建立索引
     *
     */
    @Field(type = FieldType.Text, analyzer = "ik_max_word",store = true)
    private String name;

    @Field(index = false, type = FieldType.Text)
    private String description;

    private BigDecimal price;

    private String authorName;

}

3.创建repository

@Repository
public interface BookRepository extends ElasticsearchRepository<BookDO, Long> {

	List<BookDO> findBookDOByAuthorNameAndAndPriceBetween(String name, Integer price);

}

4.创建service

/**
 * elasticsearch中本没有修改,它是先删除再新增
 * elasticsearch本质也是存储数据,它不支持事物
 */
@Service
@Slf4j
public class BookService {

    /**
     * 用于创建和删除索引
     */	
    @Autowired
    private ElasticsearchOperations operations;

    /**
     * 创建索引
     */
    public void createIndex(String indexName) {
        // 创建索引,会根据BookDO类的@Document注解信息来创建
        operations.createIndex(BookDO.class);
    	// 配置映射,会根据BookDO类中的id、Field等字段来自动完成映射
        operations.putMapping(BookDO.class);
    	//创建指定名字的索引
//        operations.createIndex(indexName);
//        operations.putMapping(OrderDO.class);
    }

    /**
     * 删除索引
     */
    public void delete(String indexName) {
        operations.deleteIndex(BookDO.class);
        // 根据索引名字删除
    	operations.deleteIndex(indexName);
    }

    /**
     * ---------------------------- 使用Repository查询,类似于jpa,进行索引的增删改查 ---------------------------------------
     */
    @Autowired
    private BookRepository bookRepository;

    /**
     * 保存图书
     *
     * @param bookDO
     * @return
     */
    public BookDO save(BookDO bookDO) {
    	BookDO result = bookRepository.save(bookDO);
        return result;
    }

    /**
     * 根据ID删除
     *
     * @param id
     */
    public void deleteById(Long id) {
    	bookRepository.deleteById(id);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    public Optional<BookDO> findById(Long id) {
        return bookRepository.findById(id);
    }

    /**
     * 根据ID列表查询
     *
     * @param ids
     * @return
     */
    public Iterable<BookDO> findAllById(List<Long> ids) {
        return bookRepository.findAllById(ids);
    }

    /**
     * 查询全部,分页,排序
     */
    public void findAll() {
    	//查询全部
        Iterable<BookDO> all = bookRepository.findAll();
    	log.info("all:"+JSONObject.toJSONString(all.iterator()));
        //排序查询全部
    	Iterable<BookDO> sortAll = bookRepository.findAll(Sort.by("price").descending().and(Sort.by("id").ascending()));
    	log.info("sortAll:"+JSONObject.toJSONString(sortAll.iterator()));
        //根据列表ID集合查询
    	Long[] ids = new Long[1];
        ids[0] = 1L;
    	Iterable<Long> iterator = new ArrayIterator(ids);
        Iterable<BookDO> allById = bookRepository.findAllById(iterator);
    	log.info("allById:"+JSONObject.toJSONString(allById.iterator()));
        //分页
    	Page<BookDO> bookDOS = bookRepository.findAll(PageRequest.of(1, 2));
    	log.info("bookDOS:"+JSONObject.toJSONString(bookDOS.getContent()));
    }


    /**
     * ---------------------------- Repository使用QueryBuilder查询 ---------------------------------------
     */	


    public void queryBuilderSearch(String name) {
    	// 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    	// 添加基本分词查询
	//queryBuilder.withQuery(QueryBuilders.matchQuery("name", name));
	//queryBuilder.withQuery(QueryBuilders.termQuery("name", name));
        //模糊
    	queryBuilder.withQuery(QueryBuilders.fuzzyQuery("name", name));
        //范围
    	queryBuilder.withQuery(QueryBuilders.rangeQuery("price").from(3000).to(4000));
    	//逻辑与关系
    	queryBuilder.withQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("name", name))
            .must(QueryBuilders.termQuery("authorName", name))
	    );
	    // 搜索,获取结果
      Page<BookDO> items = this.bookRepository.search(queryBuilder.build());
	    // 总条数
    long total = items.getTotalElements();
	    log.info("total = " + total);
 	   for (BookDO bookDO : items) {
 	       log.info(bookDO.toString());
  	  }
  }


}

注意事项:

1:es版本更新过快很多不兼容,本文使用elasticsearch6.8.4和springboot2.2.1版本
2:es通过mysql的binlog同步数据
3:

kibana的es查询语句:

1、查询全部:

GET /index_name/_search
{
  "query": {
    "match_all": {
    }
  }
}

2、根据字段匹配


3、查询执行情况

GET /index_name/_stats

个人博客地址:https://ailijie.top