在mac上很简单,brew install elasticsearch。安装完成后启动,brew services start ElasticSearch就可以了。然后访问http://localhost:9200/,出现一个json串的界面就OK了。9200是http的端口,9300是给java用户的端口。
如果是linux,看看这篇http://blog.csdn.net/cwenao/article/details/54943505,包括修改cluster.name和network.host的作用。如果不修改cluster.name那么系统是有默认的值,在第三步设置application.yml时可以看到。如果是配置远程elasticsearch集群,则设置cluster.nodes为远程的地址。
这里我们什么都不改,默认就是本机。
用idea新建,勾选web和nosql里的elasticsearch选项,等待创建完成即可。
起初我用spring boot1.5.3创建的,运行时死活报一个类找不到,后改用最新的2.0.0创建的就好了。
4.0.0
com.example
testelasticaearch
0.0.1-SNAPSHOT
jar
testelasticaearch
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.0.M1
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-elasticsearch
org.springframework.boot
spring-boot-starter-web
net.java.dev.jna
jna
3.0.9
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
spring-snapshots
Spring Snapshots
https://repo.spring.io/snapshot
true
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
false
spring-snapshots
Spring Snapshots
https://repo.spring.io/snapshot
true
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
false
除了net.java.dev.jna那个是新加的,别的都是项目勾选elasticsearch后自动创建的,新加的这个依赖是因为启动后也是报类不存在,后来在网上找个jna依赖加上后就好了。
spring:
data:
elasticsearch:
#cluster-name: #默认为elasticsearch
#cluster-nodes: 127.0.0.1: #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
properties:
path:
logs: ./elasticsearch/log #elasticsearch日志存储目录
data: ./elasticsearch/data #elasticsearch数据存储目录
我直接用http://www.tianshouzhi.com/api/tutorials/springboot/101这篇文章里的类。
把Author类和Tutorial类复制过来,还有Article类。简单说一下Article类。
package com.example.demo.pojo;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
import java.util.Date;
/**
* Created by admin on 17/6/1.
*/
@Document(indexName="projectname",type="article",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
public class Article implements Serializable {
@Id
private Long id;
/**标题*/
private String title;
/**摘要*/
private String abstracts;
/**内容*/
private String content;
/**发表时间*/
private Date postTime;
/**点击率*/
private Long clickCount;
/**作者*/
private Author author;
/**所属教程*/
private Tutorial tutorial;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAbstracts() {
return abstracts;
}
public void setAbstracts(String abstracts) {
this.abstracts = abstracts;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getPostTime() {
return postTime;
}
public void setPostTime(Date postTime) {
this.postTime = postTime;
}
public Long getClickCount() {
return clickCount;
}
public void setClickCount(Long clickCount) {
this.clickCount = clickCount;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Tutorial getTutorial() {
return tutorial;
}
public void setTutorial(Tutorial tutorial) {
this.tutorial = tutorial;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\'' +
", abstracts='" + abstracts + '\'' +
", content='" + content + '\'' +
", postTime=" + postTime +
", clickCount=" + clickCount +
", author=" + author +
", tutorial=" + tutorial +
'}';
}
}
@Document注解里面的几个属性,类比mysql的话是这样:
index –> DB
type –> Table
Document –> row
@Id注解加上后,在Elasticsearch里相应于该列就是主键了,在查询时就可以直接用主键查询,后面一篇会讲到。其实和mysql非常类似,基本就是一个数据库。
@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Document {
String indexName();//索引库的名称,个人建议以项目的名称命名
String type() default "";//类型,个人建议以实体的名称命名
short shards() default 5;//默认分区数
short replicas() default 1;//每个分区默认的备份数
String refreshInterval() default "1s";//刷新间隔
String indexStoreType() default "fs";//索引文件存储类型
}
加上了@Document注解之后,默认情况下这个实体中所有的属性都会被建立索引、并且分词。
我们通过@Field注解来进行详细的指定,如果没有特殊需求,那么只需要添加@Document即可。
@Field注解的定义如下:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface Field {
FieldType type() default FieldType.Auto;#自动检测属性的类型
FieldIndex index() default FieldIndex.analyzed;#默认情况下分词
DateFormat format() default DateFormat.none;
String pattern() default "";
boolean store() default false;#默认情况下不存储原文
String searchAnalyzer() default "";#指定字段搜索时使用的分词器
String indexAnalyzer() default "";#指定字段建立索引时指定的分词器
String[] ignoreFields() default {};#如果某个字段需要被忽略
boolean includeInParent() default false;
}
Dao:
public interface ArticleSearchRepository extends ElasticsearchRepository {
}
1
2
controller:
package com.example.demo;
import com.example.demo.pojo.Article;
import com.example.demo.pojo.Author;
import com.example.demo.pojo.Tutorial;
import com.example.demo.repository.ArticleSearchRepository;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.Iterator;
/**
* Created by admin on 17/6/1.
*/
@RestController
public class TestController {
@Autowired
private ArticleSearchRepository articleSearchRepository;
@RequestMapping("/add")
public void testSaveArticleIndex() {
Author author = new Author();
author.setId(1L);
author.setName("tianshouzhi");
author.setRemark("java developer");
Tutorial tutorial = new Tutorial();
tutorial.setId(1L);
tutorial.setName("elastic search");
Article article = new Article();
article.setId(1L);
article.setTitle("springboot integreate elasticsearch");
article.setAbstracts("springboot integreate elasticsearch is very easy");
article.setTutorial(tutorial);
article.setAuthor(author);
article.setContent("elasticsearch based on lucene,"
+ "spring-data-elastichsearch based on elaticsearch"
+ ",this tutorial tell you how to integrete springboot with spring-data-elasticsearch");
article.setPostTime(new Date());
article.setClickCount(1L);
articleSearchRepository.save(article);
}
@RequestMapping("/query")
public void testSearch() {
String queryString = "springboot";//搜索关键字
QueryStringQueryBuilder builder = new QueryStringQueryBuilder(queryString);
Iterable searchResult = articleSearchRepository.search(builder);
Iterator iterator = searchResult.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
启动项目,先执行add,往elasticsearch添加一条数据,然后再访问query即可看到结果了。
其实非常类似于普通的DB查询,还支持很多条件查询,findAll,findTop之类的,就是JPA那一套可以直接用,因为继承的ElasticsearchRepository本身就是一个PagingAndSortingRepository。