准备

引用

  1. <!--es基础包-->
  2. <dependency>
  3. <groupId>org.elasticsearch</groupId>
  4. <artifactId>elasticsearch</artifactId>
  5. <version>5.6.8</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.elasticsearch.client</groupId>
  9. <artifactId>transport</artifactId>
  10. <version>5.6.8</version>
  11. </dependency>
  12. <!--json-->
  13. <dependency>
  14. <groupId>com.fasterxml.jackson.core</groupId>
  15. <artifactId>jackson-databind</artifactId>
  16. <version>2.8.1</version>
  17. </dependency>
  18. <!--springDataElasticSearch-->
  19. <dependency>
  20. <groupId>org.springframework.data</groupId>
  21. <artifactId>spring-data-elasticsearch</artifactId>
  22. <version>3.0.5.RELEASE</version>
  23. <exclusions>
  24. <exclusion>
  25. <groupId>org.elasticsearch.plugin</groupId>
  26. <artifactId>transport-netty4-client</artifactId>
  27. </exclusion>
  28. </exclusions>
  29. </dependency>


配置


applicationContext.xml

  1. <elasticsearch:transport-client id="client"
  2. cluster-name="my-elasticsearch"
  3. cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303"/>
  4. <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
  5. <constructor-arg name="client" ref="client"/>
  6. </bean>
  7. <!--dao的扫描器-->
  8. <elasticsearch:repositories base-package="com.itheima.reopstory"/>

索引库

创建示例:

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration("classpath:applicationContext.xml")
  3. public class SprintDataElasticSearchTest {
  4. @Autowired
  5. private ElasticsearchTemplate template;
  6. @Test
  7. public void createIndex() throws Exception {
  8. template.createIndex("blog3");
  9. }
  10. }

删除

  1. template.deleteIndex(Article.class);
  2. <!--或者-->
  3. template.deleteIndex("blog2");

设置mapping信息

实体类

  1. @Document(indexName = "blog3", type = "article")
  2. public class Article {
  3. @Id
  4. @Field(type = FieldType.Long, store = true)
  5. private long id;
  6. @Field(type = FieldType.text, store = true, analyzer = "ik_max_word")
  7. private String title;
  8. @Field(type = FieldType.text, store = true, analyzer = "ik_max_word")
  9. private String content;
  10. ………………………………
  11. }

设置mapping

  1. template.putMapping(Article.class);

创建索引库并设置mapping

  1. template.createIndex(Article.class);
  2. template.putMapping(Article.class);

文档的操作

准备

dao层

  1. public interface ArticleDao extends ElasticsearchRepository<Article, Long> {
  2. }

xml配置包扫描

  1. <elasticsearch:repositories base-package="com.itheima.reopstory"/>

新建

  1. //创建一个Article对象
  2. Article article = new Article();
  3. article.setId(1);
  4. article.setTitle("测试文档");
  5. article.setContent("测试文档的内容");
  6. //写入索引库
  7. articleDao.save(article);

删除

  1. articleDao.deleteById(1l);

修改

  1. Optional<Article> optional = articleDao.findById(1l);
  2. Article article = optional.get();
  3. article.setTitle("女子网恋被骗168万 对方自称在迪拜经商美国男子");
  4. articleDao.save(article);

查询

  • 根据ID
  • 根据方法命名规则查询

    直接在dao层根据规则创建方法即可使用

关键字 命名规则 解释 示例
and findByField1AndField2 根据Field1和Field2获得数据 findByTitleAndContent
or findByField1OrField2 根据Field1或Field2获得数据 findByTitleOrContent
is findByField 根据Field获得数据 findByTitle
not findByFieldNot 根据Field获得补集数据 findByTitleNot
between findByFieldBetween 获得指定范围的数据 findByPriceBetween
lessThanEqual findByFieldLessThan 获得小于等于指定值的数据 findByPriceLessThan
  • 分词查询
  1. SearchQuery query = new NativeSearchQuery(
  2. QueryBuilders.queryStringQuery("张三是一个什么样的人")
  3. .defaultField("username"));
  4. //设置分页信息
  5. query.setPageable(PageRequest.of(0, 5));
  6. List<EsUser> list = elasticsearchTemplate.queryForList(query, EsUser.class);
  • 高亮分词查询
  1. @Test
  2. public void testQueryHighlighing() {
  3. NativeSearchQuery query = new NativeSearchQueryBuilder()
  4. .withQuery(QueryBuilders.queryStringQuery("张三是一个什么样的人").defaultField("title"))
  5. .withHighlightFields(new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"))
  6. .build();
  7. //设置分页信息
  8. query.setPageable(PageRequest.of(0, 5));
  9. AggregatedPage<UserEntity> page = elasticsearchTemplate.queryForPage(query, UserEntity.class, new SearchResultMapper() {
  10. @Override
  11. public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
  12. SearchHits searchHits = searchResponse.getHits();
  13. SearchHit[] hits = searchHits.getHits();
  14. List<UserEntity> userList = new ArrayList<>();
  15. for (SearchHit hit : hits) {
  16. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  17. Text title = highlightFields.get("title").getFragments()[0];
  18. Map<String, Object> source = hit.getSource();
  19. UserEntity user = new UserEntity();
  20. user.setId(Long.parseLong(source.get("id").toString()));
  21. user.setTitle(title.toString());
  22. user.setContent((String) source.get("content"));
  23. userList.add(user);
  24. }
  25. AggregatedPage aggregatedPage = new AggregatedPageImpl(userList,pageable,searchHits.getTotalHits());
  26. return aggregatedPage;
  27. }
  28. });
  29. List<UserEntity> userList = page.getContent();
  30. long totalElements = page.getTotalElements();
  31. System.out.println(totalElements);
  32. for (UserEntity user : userList) {
  33. System.out.println(user);
  34. }
  35. }