Spring Data ElasticSearch入门案例


创建maven工程elasticsearch_springdata

基于maven导入坐标

导入spring data elasticsearch,它是对elasticsearch API的简化封装。


<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>


导入spring test和junit,编写测试用力需要进行测试。


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>


导入slf4j-log4j日志包。


<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>


创建applicationContext.xml和log4j.properties配置文件,在applicationContext.xml配置文件中引入spring data elasticsearch名称空间。


xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="
http://www.springframework.org/schema/data/elasticsearch
http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"


log4j配置文件


### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout


创建domain,dao,service包

编写dao,继承ElasticSearchRepository接口


public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> { }


配置applicationContext.xml,扫描dao包自动创建dao的实现。


<!-- 扫描dao包  自动创建实现 -->
<elasticsearch:repositories base-package="cn.niwotaxuexiba.dao" />


编写service


@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleRepository articleRepository;
public void save(Article article){
articleRepository.save(article);
}
}


配置applicationContext.xml,扫描service包


<!-- 扫描service包 -->
<context:component-scan base-package="cn.niwotaxuexiba.service" />


配置applicationContext.xml连接elasticsearch.


<!-- 配置elasticsearch连接 -->
<elasticsearch:transport-client id="client" cluster-nodes="localhost:9300"/>
<!-- spring data elasticsearch DAO必须依赖elasticsearchTemplate -->
<bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean>


在使用spring data elasticsearch创建索引和映射时,需要将索引和映射信息配置在实体类上面。

@Document文档对象(索引信息、文档类型)

@Id文档主键,是唯一标识

@Field每个文档的字段配置(类型、是否分词、是否存储、分词器)


@Document(indexName = "blog3",type="article")
public class Article {
@Id
@Field(index=FieldIndex.not_analyzed,store=true,type=FieldType.Integer)
private Integer id;
@Field(index=FieldIndex.analyzed,analyzer="ik",store=true,searchAnalyzer="ik",type=FieldType.String)
private String title;
@Field(index=FieldIndex.analyzed,analyzer="ik",store=true,searchAnalyzer="ik",type=FieldType.String)
private String content;
}


通过ElasticsearchTemplate创建索引和添加映射


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class ArticleServiceImplTest {
@Autowired
private ArticleService articleService;
@Autowired
private Client client;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Test
public void createIndex() {
elasticsearchTemplate.createIndex(Article.class);
elasticsearchTemplate.putMapping(Article.class);
}
}


spring data search CRUD操作:

CrudRepository提供增删改查save/delete/findAll/findOne的方法;

PagingAndSortingRepository提供分页和排序的方法。


@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleRepository articleRepository;
@Override
public void save(Article article){
articleRepository.save(article);
}
@Override
public void delete(Article article) {
// TODO Auto-generated method stub
articleRepository.delete(article);
}
@Override
public Article findOne(Integer id) {
// TODO Auto-generated method stub
return articleRepository.findOne(id);
}
@Override
public Iterable<Article> findAll() {
// TODO Auto-generated method stub
return articleRepository.findAll();
}
}


查询标题的方法

service


@Override
public List<Article> findByTitle(String title) {
// TODO Auto-generated method stub
return articleRepository.findByTitle(title);
}


dao


public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> {

List<Article> findByTitle(String title);
}


分页条件查询,需要在查询方法中,传入Pageable对象。

service


public Page<Article> findByTitle(String title, Pageable pageable) {
// TODO Auto-generated method stub
return articleRepository.findByTitle(title,pageable);
}


dao


public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> {

Page<Article> findByTitle(String title, Pageable pageable);

}