官网:https://www.elastic.co/cn/
官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html
1.安装elastic环境(win10)
2.Elasticsearch基础(postman)
3.SpringBoot集成Elasticsearch
注:SpringBoot易于其他组件如Redis等产生冲突,建议测试时先单独测试,之后再集成。
1.安装elastic环境(win10)
下载地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/getting-started-install.html
安装与运行的权限问题:
以管理员身份运行cmd,安装elasticsearch。
然后进入安装目录的bin目录下以管理员身份运行elasticsearch.exe。
(如果添加到桌面快捷方式,添加以管理员身份运行权限)
启动完成后访问http://localhost:9200/
2.Elasticsearch基础(postman)
文档:https://www.elastic.co/guide/cn/elasticsearch/guide/current/_indexing_employee_documents.html
创建3个索引
检索文档
http://localhost:9200/megacorp/employee/_search
_search搜索所有
http://localhost:9200/megacorp/employee/_search?q=last_name:Smith
带条件查询
使用查询表达式查询:
全文搜索:
模糊查询
精准查询
高亮搜索
3.SpringBoot集成Elasticsearch
版本适配问题(2.1.6):
spring-boot-starter-data-elasticsearch默认的spring-data-elasticsearch版本为3.1.9
https://github.com/spring-projects/spring-data-elasticsearch
适配版本为6.2.2
卸载Elasticsearch(权限问题):
以管理员身份运行cmd:
wmic
product list
复制IdentifyingNumber
输入quit退出
quit
输入
msiexec x/IdentifyingNumber
pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
记坑:如果SpringBoot启动报错,在主类加上
//elasticsearch 启动报错
System.setProperty("es.set.netty.runtime.available.processors","false");
配置yaml
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300
编写实体类
package zkrun.top.reference.bean;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
@Document(indexName = "elastic",type = "hq")
public class Person implements Serializable {
private String name;
private Integer age;
private String email;
public Person() {
}
public Person(String name, Integer age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", email='" + email + '\'' +
'}';
}
}
继承ElasticsearchRepository接口
注:接口参数对应实体类的类名,ID
package zkrun.top.reference.repository;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import zkrun.top.reference.bean.ElasticBean;
public interface BeanRepository extends ElasticsearchRepository<ElasticBean,Integer> {
}
创建一个文档
//===========================
@Autowired
BeanRepository beanRepository;
//创建一个文档
@Test
public void elasticTest()
{
ElasticBean elasticBean = new ElasticBean(1,"hq",21,"glaring1shadow@sina.com");
beanRepository.index(elasticBean);
}