官网:Elasticsearch 7.8.0 | Elastic
大家下载所需要的安装包即可。然后解压缩:
Elasticsearch是通过java编写的,所以自带jdk。多好,下载Elasticsearch赠送jdk? 0.0,不过一般我们用自己的jdk。
要启动Elasticsearch服务,就直接进入bin目录,并打开elasticsearch.bat文件。
这样就启动好了。
注意:9300端口为Elasticsearch集群间组件的通信端口,9200端口为浏览器访问的http协议RESTful端口。
启动之后,可以打开浏览器:localhost:9200
可能你们的和我这个描述不一样,因为我修改了它的配置文件,但是只要出现这种类似的,就说明启动成功了。
注意:在启动的时候,由于版本问题,但凡使用超过java11的版本都有可能出现启动失败问题。
这个东西在启动的时候就有了,意思是这个版本用的是java11,但是我们用java8是完全没有问题的。但到了Java17的时候很多东西都改变了。当然版本小于1.8也会出错。
所以用java17运行Elasticsearch 7.8.0的时候会有很大机率出错。
正排索引(Forward Index):
倒排索引(Inverted Index):
举例说明:
文档1: "机器学习是人工智能的一个重要分支。"
文档2: "深度学习在图像识别领域取得了显著的成果。"
正排索引示例:
文档1: [机器学习, 人工智能, 重要, 分支]
文档2: [深度学习, 图像识别, 显著, 成果]
倒排索引示例:
机器学习: [文档1]
人工智能: [文档1]
重要: [文档1]
分支: [文档1]
深度学习: [文档2]
图像识别: [文档2]
显著: [文档2]
成果: [文档2]
而我们的Elasticsearch使用的就是倒排索引
RESTful(Representational State Transfer)是一种基于资源的软件架构风格,通常用于设计网络应用程序的 API。以下是一些与RESTful风格相关的主要原则和特征:
资源(Resources):
表现层(Representation):
状态转移(State Transfer):
统一接口(Uniform Interface):
无状态(Stateless):
可缓存性(Cacheability):
按需扩展性(Layered System):
无连接(Stateless Communication):
RESTful 风格的设计使得系统更具可伸缩性、可维护性,同时提供了清晰的接口,使得不同系统能够有效地协同工作。这种风格通常用于构建 Web 服务和 API。
注意:Elasticsearch 允许GET、PUT、HEAD、DELETE请求。而post和put是针对文档的,但是put要求幂等性,而post并不要求,如果没有定义主键,Elasticsearch的文档创建的时候每次返回的主键都是不一样的,所以用put会报错
对比关系型数据库,创建索引就等同于创建数据库。
在Postman中,向ES服务器发出Put请求:http://127.0.0.1:9200/cyl
哦对了,这个工具用的是postman
在Postman中,向ES服务器发出GET请求:http://127.0.0.1:9200/cyl
如果想查询所有的索引:GET下面命令
http://127.0.0.1:9200/_cat/indices?v
在Postman中,向ES服务器发出DELETE请求:http://127.0.0.1:9200/cyl
删除成功。
Post 请求http://127.0.0.1:9200/cyl/_doc
{
"title": "Elasticsearch Introduction",
"content": "Elasticsearch is a powerful search engine."
}
由于幂等性原因,我加了个自定义主键,就可以用put了。
PUT 请求http://127.0.0.1:9200/cyl/_doc/1001
GET请求:http://127.0.0.1:9200/cyl/_doc/1001
查询cyl索引下的全部数据
Get请求:http://127.0.0.1:9200/cyl/_search
DELETE 请求http://127.0.0.1:9200/cyl/_doc/1001
Put请求?http://127.0.0.1:9200/cyl/_doc/1001
{
"title": "Elasticsearch Introduction",
"content": "Elasticsearch is a powerful search engine.",
"cyl": "tql"
}
Post请求:http://127.0.0.1:9200/cyl/_update/1001
{
"doc":{
"content": "Elasticsearch is not good search engine."
}
}
Get请求:http://127.0.0.1:9200/cyl/_search?q=cyl:tql
q后面接字段:值
一般是按照请求体查询。
Get请求:http://127.0.0.1:9200/cyl/_search
{
"query":{
"match":{
"cyl":"tql"
}
}
}
{
"query":{
"match_all":{
}
}
}
{
"query":{
"match_all":{
}
},
"from":0,
"size":1
}
{
"query":{
"match_all":{
}
},
"from":0,
"size":1,
"_source":"title"
}
{
"query":{
"match_all":{
}
},
"from":0,
"size":1,
"_source":"title",
"sort":{
"title":{
"order":"desc"
}
}
}
由于不是数字,可能会出错。
must
、should
、must_not
?等关键词组合多个查询条件。must
:所有查询条件都必须匹配。should
:至少有一个查询条件匹配,增加文档的相关性。must_not
:查询条件不能匹配。{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } },
{ "range": { "publish_date": { "gte": "2022-01-01" } } }
],
"should": [
{ "match": { "content": "search engine" } }
],
"must_not": [
{ "term": { "status": "archived" } }
]
}
}
}
{
"query": {
"range": {
"publish_date": {
"gte": "2022-01-01",
"lte": "2022-12-31"
}
}
}
}
{
"query": {
"wildcard": {
"title.keyword": "elasticsearch*"
}
}
}
{
"query": {
"fuzzy": {
"title": {
"value": "elasticsearch",
"fuzziness": 2
}
}
}
}
match
、match_phrase
等查询来执行全文检索。{
"query": {
"match": {
"content": "Elasticsearch tutorial"
}
}
}
上述查询将返回包含 "Elasticsearch" 和 "tutorial" 中任意一个或两者的文档。
term
或terms
查询来执行完全匹配。{
"query": {
"term": {
"title.keyword": "Elasticsearch"
}
}
}
上述查询将返回具有 "title.keyword" 字段值完全等于 "Elasticsearch" 的文档。注意,这里使用了 ".keyword" 后缀,表示确切匹配。
{
"aggs": {
"group_by_category": {
"terms": {
"field": "category.keyword"
}
}
}
}
{
"aggs": {
"price_ranges": {
"range": {
"field": "price",
"ranges": [
{ "from": 0, "to": 50 },
{ "from": 50, "to": 100 },
{ "from": 100, "to": 200 }
]
}
}
}
}
日期直方图聚合用于按时间间隔对文档进行分组,并统计每个时间间隔的文档数量。
{
"aggs": {
"monthly_sales": {
"date_histogram": {
"field": "sale_date",
"calendar_interval": "month"
}
}
}
}
{
"aggs": {
"group_by_category": {
"terms": {
"field": "category.keyword"
},
"aggs": {
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
在Elasticsearch中,映射(Mapping)是定义索引中字段的数据类型及其属性的过程。每个索引都有一个映射,而映射定义了索引中存储的数据的结构和特性。以下是关于Elasticsearch映射的一些重要概念:
字段数据类型(Field Data Types):
动态映射(Dynamic Mapping):
映射属性(Mapping Properties):
嵌套字段(Nested Fields):
复杂字段类型(Complex Field Types):
索引模板(Index Templates):
以下是一个简单的映射示例,用于说明映射的基本结构:
{
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "standard"
},
"price": {
"type": "float"
},
"timestamp": {
"type": "date"
},
"tags": {
"type": "keyword"
},
"location": {
"type": "geo_point"
}
}
}
}
上述映射定义了一个包含标题、价格、时间戳、标签和地理位置的文档的索引。每个字段都有指定的数据类型和可能的映射属性。
pom文件:
<?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>org.cyl</groupId>
<artifactId>test01</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package org.cyl;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//关闭es客户端
client.close();
}
}
package org.cyl;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import java.io.IOException;
public class ESIndex_Create {
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//创建索引
CreateIndexRequest request = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
//响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("索引操作:"+acknowledged);
//关闭es客户端
client.close();
}
}
package org.cyl;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import java.io.IOException;
public class ESIndex_Search {
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询索引
GetIndexRequest request = new GetIndexRequest("user");
GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);
//响应状态
System.out.println(getIndexResponse.getAliases());
System.out.println(getIndexResponse.getMappings());
System.out.println(getIndexResponse.getSettings());
//关闭es客户端
client.close();
}
}
package org.cyl;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import java.io.IOException;
public class ESIndex_Delete {
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询索引
DeleteIndexRequest request = new DeleteIndexRequest("user");
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
//响应状态
System.out.println("删除索引:"+delete.isAcknowledged());
//关闭es客户端
client.close();
}
}
创建user类
package org.cyl;
public class User {
private String name;
private String sex;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
添加pom文件内容
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
package org.cyl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class ESDoc_Insert {
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//插入数据
IndexRequest request=new IndexRequest();
request.index("user").id("1001");
User user=new User();
user.setName("zhangsan");
user.setAge(30);
user.setSex("男");
//向ES插入数据,必须将数据转换为json格式
ObjectMapper mapper=new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭es客户端
client.close();
}
}
package org.cyl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class ESDoc_Update {
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//修改数据
UpdateRequest request=new UpdateRequest();
request.index("user").id("1001");
request.doc(XContentType.JSON,"sex","女");
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭es客户端
client.close();
}
}
package org.cyl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class ESDoc_Get {
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
GetRequest request=new GetRequest();
request.index("user").id("1001");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());
//关闭es客户端
client.close();
}
}
package org.cyl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.engine.Engine;
import java.io.IOException;
public class ESDoc_Get {
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
DeleteRequest request=new DeleteRequest();
request.index("user").id("1001");
DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
System.out.println(delete.getResult());
//关闭es客户端
client.close();
}
}
当然可以批量删除和批量插入。
然后解压:
双击即可开启:
?
? ? ?首先,在Spring Boot项目的pom.xml
文件中添加Elasticsearch的依赖。例如,使用Spring Data Elasticsearch提供的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
在application.properties
或application.yml
中配置Elasticsearch连接信息,包括集群地址、端口等。
spring.data.elasticsearch.cluster-nodes=localhost:9200
创建与Elasticsearch索引文档对应的实体类,并使用注解配置映射关系。
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "your_index_name", type = "your_type_name")
public class YourEntity {
@Id
private String id;
private String field1;
private String field2;
// Getters and setters
}
创建一个继承自ElasticsearchRepository
的接口,用于操作Elasticsearch索引。
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface YourEntityRepository extends ElasticsearchRepository<YourEntity, String> {
// Custom queries if needed
}
在服务或控制器中使用创建的Repository接口进行Elasticsearch索引的增、删、改、查等操作。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class YourEntityService {
@Autowired
private YourEntityRepository repository;
public YourEntity save(YourEntity entity) {
return repository.save(entity);
}
// Other methods for CRUD operations
}
启动Spring Boot应用程序,并确保Elasticsearch服务器在指定的地址和端口上运行。