Take a look at the most introductory examples. One: Install Elasticsearch.
It's simple on Mac, brew install Elasticsearch. When the installation is complete, brew services start Elasticsearch is ready. Then access http://localhost:9200/, the interface of a JSON string will be OK. 9200 is the port for HTTP, and 9300 is the port for Java users.
If it's Linux, look at this http://blog.csdn.net/cwenao/article/details/54943505, including modifying the role of Cluster.name and Network.host. If you do not modify cluster.name then the system has a default value, which you can see when you set the APPLICATION.YML in the third step. If you are configuring a remote Elasticsearch cluster, set Cluster.nodes as the remote address.
Here we do not change anything, the default is the machine. II: Create a new spring boot Elasticsearch project.
Create new with idea, tick the Elasticsearch option in the Web and NoSQL, and wait for the creation to complete.
At first I created it with Spring boot1.5.3, and the runtime reported that a class could not be found, and then it was better to use the newest 2.0.0.
<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.exam Ple</groupid> <artifactId>testelasticaearch</artifactId> <version>0.0.1-snapshot</ version> <packaging>jar</packaging> <name>testelasticaearch</name> <description >demo Project for Spring boot</description> <parent> <GROUPID>ORG.SPRINGFRAMEWORK.BOOT&L T;/groupid> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.M1< /version> <relativePath/> <!--lookup parent from repository to </parent> <prope Rties> <project.build.sourceencoding>utF-8</project.build.sourceencoding> <project.reporting.outputencoding>utf-8</ project.reporting.outputencoding> <java.version>1.8</java.version> </properties> <
;d ependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <DEP Endency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot- Starter-web</artifactid> </dependency> <dependency> <groupid>net.java. Dev.jna</groupid> <artifactId>jna</artifactId> <version>3.0.9</version&
Gt
</dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> </dependen cies> <build> <plugins> <plugin> <GROUPID>ORG.SPRINGFR Amework.boot</groupid> <artifactId>spring-boot-maven-plugin</artifactId> <
;/plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>spring snapshots</name> <url>https:/
/repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones </id> <name>spring milestones</name> <url>https://repo.spring.io/milestone
</url> <snapshots> <enabled>false</enabled> </snapshots> </reposi tory> </repositories> <pluginRepositories> <pluginRepository> <id> spring-snapshots</id> <name>spring snapshots</name> <url>https://repo.spri Ng.io/snapshot</url> <snapshots> <enabled>true</enabled> & lt;/snapshots> </pluginRepository> <pluginRepository> <id>spring-mileston es</id> <name>spring milestones</name> <url>https://repo.spring.io/milesto ne</url> <snapshots> <enabled>false</enabled> </snapsho
ts> </pluginRepository> </pluginRepositories> </project>
In addition to Net.java.dev.jna that is new, and other items are automatically created after the project check Elasticsearch, the new addition of this dependency is because after the launch is also reported class does not exist, and later on the internet to find a JNA dependency plus after the good. Three: Configure the Yml file.
Spring:
data:
elasticsearch:
#cluster-name: #默认为elasticsearch
#cluster-nodes:127.0.0.1: # Configure ES node information, comma delimited, if not specified, start Clientnode
properties:
Path:
logs:./elasticsearch/log #elasticsearch日志存储目录
data:./elasticsearch/data #elasticsearch数据存储目录
Four: Create the JavaBean file.
I use http://www.tianshouzhi.com/api/tutorials/springboot/101 the class in this article directly.
Copy the author class and the Tutorial class, as well as the article class. Simply say the article class.
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;
/** Title */private String title;
/** Abstract */private String abstracts;
/** Contents */private String content;
/** Publish time */private Date posttime;
/** Ctr */Private Long clickcount;
/** Author */private Author Author;
/** Tutorial */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;
The 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= "+ pos Ttime + ", clickcount=" + Clickcount + ", author=" + author + ", tutorial=
"+ Tutorial + '} '; }
}
@Document a few of the attributes in the annotation, the analogy to MySQL is this:
Index–> DB
Type–> Table
Document–> row
@Id Note Plus, in the elasticsearch corresponding to the column is the primary key, in the query can be directly with the primary key query, the next one will talk about. In fact, and MySQL very similar, basically is a database.
@Persistent
@Inherited
@Retention (retentionpolicy.runtime)
@Target ({elementtype.type}) public
@ Interface Document {
string indexname ();//The name of the index library, the individual recommends naming
String type () default "" For the name of the project, or type, which is named after the entity name Short
shards () default 5;//partition number short
replicas () default 1;//number of backups per partition
String RefreshInterval () "1s";//Refresh Interval
String indexstoretype () default "FS";//index file storage type
}
With the @document annotation in place, all properties in this entity are indexed and participle by default.
We use @field annotations for detailed designation, and if there are no special needs, then just add @document.
@Field annotations are defined as follows:
@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;
}
V: DAO and Controller
Dao:
Public interface Articlesearchrepository extends Elasticsearchrepository<article, long> {
}
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 Articlesearchrepositor
Y
@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 what 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";//Search keyword
Querystringquerybuilder builder = new Querystringquerybuilder (queryString);
Iterable<article> SearchResult = Articlesearchrepository.search (builder); iterator<article> Iterator = Searchresult.iteratoR ();
while (Iterator.hasnext ()) {System.out.println (Iterator.next ());
}
}
}
Start the project by executing add, adding a piece of data to Elasticsearch, and then accessing query to see the results.
is very similar to ordinary DB queries, but also supports a lot of conditional queries, findall,findtop and so on, that is, JPA that set can be used directly, Because the inherited elasticsearchrepository itself is a pagingandsortingrepository.
Reference: http://www.cnblogs.com/softidea/p/6102796.html