ElasticSearch增删改查
时间: 2023-12-25 14:05:19 浏览: 29
ElasticSearch是一种基于Lucene的分布式搜索和分析引擎,支持全文搜索、结构化搜索、地理位置搜索等多种搜索方式。在ElasticSearch中,增删改查操作可以通过REST API实现。
1. 增加数据
使用HTTP POST方法向ElasticSearch中的索引中添加数据,例如:
```
POST /my_index/my_type
{
"name": "John Doe",
"age": 25,
"email": "johndoe@email.com"
}
```
2. 删除数据
使用HTTP DELETE方法从ElasticSearch中的索引中删除数据,例如:
```
DELETE /my_index/my_type/1
```
3. 更新数据
使用HTTP PUT方法或者HTTP POST方法更新ElasticSearch中的索引中的数据,例如:
```
PUT /my_index/my_type/1
{
"name": "John Doe",
"age": 26,
"email": "johndoe@email.com"
}
```
4. 查询数据
使用HTTP GET方法查询ElasticSearch中的索引中的数据,例如:
```
GET /my_index/my_type/_search?q=name:John
```
以上是基本的增删改查操作,ElasticSearch还支持更丰富的搜索方式,例如filter、aggregations等,可以根据具体需求进行使用。
相关问题
springboot 整合 Elasticsearch 增删改查代码
好的,以下是一个简单的Spring Boot整合Elasticsearch实现增删改查的示例代码:
插入数据:
```
@Autowired
private ElasticsearchTemplate esTemplate;
IndexQuery query = new IndexQueryBuilder()
.withId("1")
.withObject(new User("John", "Doe"))
.build();
String documentId = esTemplate.index(query);
```
查询数据:
```
@Autowired
private ElasticsearchTemplate esTemplate;
GetQuery query = new GetQuery();
query.setId("1");
User user = esTemplate.queryForObject(query, User.class);
```
更新数据:
```
@Autowired
private ElasticsearchTemplate esTemplate;
IndexQuery query = new IndexQueryBuilder()
.withId("1")
.withObject(new User("Jane", "Doe"))
.build();
esTemplate.index(query);
```
删除数据:
```
@Autowired
private ElasticsearchTemplate esTemplate;
DeleteQuery query = new DeleteQuery();
query.setId("1");
esTemplate.delete(query, User.class);
```
注意:这只是一个简单的示例代码,实际应用中可能需要更复杂的查询和数据处理。
Elasticsearch增删改查 之 —— Get查询
在 Elasticsearch 中,可以使用 GET API 进行单个文档的查询,GET API 的使用方法如下:
```http
GET /index/_doc/id
```
其中,`index` 表示索引名称,`_doc` 表示文档类型,`id` 表示文档的唯一标识符。
例如,查询索引名为 `my_index`、文档类型为 `_doc`、文档 ID 为 `1` 的文档,可以使用以下命令:
```http
GET /my_index/_doc/1
```
如果查询成功,Elasticsearch 会返回以下响应:
```json
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"found": true,
"_source": {
"title": "Elasticsearch",
"author": "John",
"content": "Elasticsearch is a distributed, RESTful search and analytics engine.",
"publish_time": "2021-01-01"
}
}
```
其中,`_index` 表示索引名称,`_type` 表示文档类型,`_id` 表示文档的唯一标识符,`_version` 表示文档的版本号,`_source` 表示文档的内容。
如果查询的文档不存在,Elasticsearch 会返回以下响应:
```json
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"found": false
}
```
其中,`found` 表示查询的文档是否存在。