准备
引用
<!--es基础包--><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>5.6.8</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>transport</artifactId><version>5.6.8</version></dependency><!--json--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.1</version></dependency><!--springDataElasticSearch--><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-elasticsearch</artifactId><version>3.0.5.RELEASE</version><exclusions><exclusion><groupId>org.elasticsearch.plugin</groupId><artifactId>transport-netty4-client</artifactId></exclusion></exclusions></dependency>
配置
applicationContext.xml
<elasticsearch:transport-client id="client"cluster-name="my-elasticsearch"cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303"/><bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"><constructor-arg name="client" ref="client"/></bean><!--dao的扫描器--><elasticsearch:repositories base-package="com.itheima.reopstory"/>
索引库
创建示例:
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class SprintDataElasticSearchTest {@Autowiredprivate ElasticsearchTemplate template;@Testpublic void createIndex() throws Exception {template.createIndex("blog3");}}
删除
template.deleteIndex(Article.class);<!--或者-->template.deleteIndex("blog2");
设置mapping信息
实体类
@Document(indexName = "blog3", type = "article")public class Article {@Id@Field(type = FieldType.Long, store = true)private long id;@Field(type = FieldType.text, store = true, analyzer = "ik_max_word")private String title;@Field(type = FieldType.text, store = true, analyzer = "ik_max_word")private String content;………………………………}
设置mapping
template.putMapping(Article.class);
创建索引库并设置mapping
template.createIndex(Article.class);template.putMapping(Article.class);
文档的操作
准备
dao层
public interface ArticleDao extends ElasticsearchRepository<Article, Long> {}
xml配置包扫描
<elasticsearch:repositories base-package="com.itheima.reopstory"/>
新建
//创建一个Article对象Article article = new Article();article.setId(1);article.setTitle("测试文档");article.setContent("测试文档的内容");//写入索引库articleDao.save(article);
删除
articleDao.deleteById(1l);
修改
Optional<Article> optional = articleDao.findById(1l);Article article = optional.get();article.setTitle("女子网恋被骗168万 对方自称在迪拜经商美国男子");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 | 
- 分词查询
 
SearchQuery query = new NativeSearchQuery(QueryBuilders.queryStringQuery("张三是一个什么样的人").defaultField("username"));//设置分页信息query.setPageable(PageRequest.of(0, 5));List<EsUser> list = elasticsearchTemplate.queryForList(query, EsUser.class);
- 高亮分词查询
 
@Testpublic void testQueryHighlighing() {NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(QueryBuilders.queryStringQuery("张三是一个什么样的人").defaultField("title")).withHighlightFields(new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>")).build();//设置分页信息query.setPageable(PageRequest.of(0, 5));AggregatedPage<UserEntity> page = elasticsearchTemplate.queryForPage(query, UserEntity.class, new SearchResultMapper() {@Overridepublic <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {SearchHits searchHits = searchResponse.getHits();SearchHit[] hits = searchHits.getHits();List<UserEntity> userList = new ArrayList<>();for (SearchHit hit : hits) {Map<String, HighlightField> highlightFields = hit.getHighlightFields();Text title = highlightFields.get("title").getFragments()[0];Map<String, Object> source = hit.getSource();UserEntity user = new UserEntity();user.setId(Long.parseLong(source.get("id").toString()));user.setTitle(title.toString());user.setContent((String) source.get("content"));userList.add(user);}AggregatedPage aggregatedPage = new AggregatedPageImpl(userList,pageable,searchHits.getTotalHits());return aggregatedPage;}});List<UserEntity> userList = page.getContent();long totalElements = page.getTotalElements();System.out.println(totalElements);for (UserEntity user : userList) {System.out.println(user);}}
