ES文档CRUD案例

wen java案例 1

本文目录导读:

ES文档CRUD案例

  1. 环境准备
  2. 创建文档(Create)
  3. 查询文档(Read)
  4. 更新文档(Update)
  5. 删除文档(Delete)
  6. 使用Java API示例
  7. 批量操作示例
  8. 实用技巧

我来为您提供Elasticsearch文档CRUD操作的详细案例。

环境准备

# 创建索引(如果不存在)
PUT /my_index
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties": {
      "id": { "type": "integer" },
      "title": { "type": "text", "analyzer": "ik_max_word" },
      "content": { "type": "text", "analyzer": "ik_max_word" },
      "tags": { "type": "keyword" },
      "price": { "type": "float" },
      "createTime": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss" }
    }
  }
}

创建文档(Create)

1 指定ID创建

POST /my_index/_doc/1
{
  "id": 1,: "Elasticsearch入门教程",
  "content": "本教程介绍Elasticsearch的基础知识",
  "tags": ["elasticsearch", "教程"],
  "price": 29.9,
  "createTime": "2023-12-01 10:00:00"
}

2 自动生成ID

POST /my_index/_doc
{
  "id": 2,: "Java编程思想",
  "content": "深入浅出讲解Java编程",
  "tags": ["Java", "编程"],
  "price": 89.0,
  "createTime": "2023-12-02 15:30:00"
}

3 批量创建

POST /my_index/_bulk
{"index": {"_id": "3"}}
{"id": 3, "title": "Python入门", "content": "Python基础教程", "tags": ["Python"], "price": 39.9, "createTime": "2023-12-03 09:00:00"}
{"index": {"_id": "4"}}
{"id": 4, "title": "Spring Boot实战", "content": "Spring Boot实战教程", "tags": ["Spring", "Java"], "price": 69.0, "createTime": "2023-12-04 14:00:00"}

查询文档(Read)

1 根据ID查询

# 查询单条文档
GET /my_index/_doc/1
# 查询文档是否存在
HEAD /my_index/_doc/1
# 返回结果示例
{
  "_index": "my_index",
  "_id": "1",
  "_version": 1,
  "_seq_no": 0,
  "_primary_term": 1,
  "found": true,
  "_source": {
    "id": 1,: "Elasticsearch入门教程",
    "content": "本教程介绍Elasticsearch的基础知识",
    "tags": ["elasticsearch", "教程"],
    "price": 29.9,
    "createTime": "2023-12-01 10:00:00"
  }
}

2 条件查询

# 查询所有文档
GET /my_index/_search
{
  "query": {
    "match_all": {}
  }
}
# 精确查询
GET /my_index/_search
{
  "query": {
    "term": { "tags": "Java" }
  }
}
# 范围查询
GET /my_index/_search
{
  "query": {
    "range": {
      "price": {
        "gte": 30,
        "lte": 80
      }
    }
  }
}
# 全文搜索
GET /my_index/_search
{
  "query": {
    "match": {
      "title": "Elasticsearch教程"
    }
  }
}

更新文档(Update)

1 全量更新(覆盖)

# 使用PUT全量更新(会覆盖原文档)
PUT /my_index/_doc/1
{
  "id": 1,: "Elasticsearch高级教程",
  "content": "高级特性详解",
  "tags": ["elasticsearch", "高级"],
  "price": 49.9,
  "createTime": "2023-12-05 10:00:00"
}

2 部分字段更新

# 使用POST局部更新
POST /my_index/_update/1
{
  "doc": {
    "price": 59.9,
    "tags": ["elasticsearch", "高级", "教程"]
  }
}
# 批量更新
POST /my_index/_update_by_query
{
  "query": {
    "term": { "tags": "Java" }
  },
  "script": {
    "source": "ctx._source.price += 10",
    "lang": "painless"
  }
}

删除文档(Delete)

1 根据ID删除

# 删除单条文档
DELETE /my_index/_doc/1
# 返回结果
{
  "_index": "my_index",
  "_id": "1",
  "_version": 2,
  "result": "deleted",
  "_shards": {
    "total": 1,
    "successful": 1,
    "failed": 0
  }
}

2 条件删除

# 根据条件删除
POST /my_index/_delete_by_query
{
  "query": {
    "range": {
      "price": {
        "lt": 30
      }
    }
  }
}
# 删除索引下所有文档
POST /my_index/_delete_by_query
{
  "query": {
    "match_all": {}
  }
}

使用Java API示例

1 Maven依赖

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.17.0</version>
</dependency>

2 创建文档

String INDEX_NAME = "my_index";
// 创建索引客户端
RestHighLevelClient client = new RestHighLevelClient(
    RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 创建文档
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("title", "Elasticsearch实战");
jsonMap.put("content", "这是内容");
jsonMap.put("price", 59.9);
jsonMap.put("tags", Arrays.asList("elasticsearch", "实战"));
IndexRequest indexRequest = new IndexRequest(INDEX_NAME)
    .id("10")
    .source(jsonMap);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println("文档ID: " + indexResponse.getId());

3 更新文档

// 部分更新
Map<String, Object> updateMap = new HashMap<>();
updateMap.put("price", 79.9);
UpdateRequest updateRequest = new UpdateRequest(INDEX_NAME, "1")
    .doc(updateMap);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);

4 删除文档

DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME, "1");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);

5 查询文档

// 根据ID查询
GetRequest getRequest = new GetRequest(INDEX_NAME, "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
// 条件查询
SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("title", "Elasticsearch"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

批量操作示例

1 批量创建/更新

POST /my_index/_bulk
{"index": {"_id": "5"}}
{"id": 5, "title": "Redis实战", "content": "Redis教程", "tags": ["Redis"], "price": 45.0, "createTime": "2023-12-06 10:00:00"}
{"update": {"_id": "2"}}
{"doc": {"price": 99.0}}
{"delete": {"_id": "3"}}
{"index": {"_id": "6"}}
{"id": 6, "title": "MySQL优化", "content": "数据库优化教程", "tags": ["MySQL"], "price": 55.0, "createTime": "2023-12-07 11:00:00"}

实用技巧

1 使用upsert

# 如果文档存在则更新,不存在则创建
POST /my_index/_update/7
{
  "script": {
    "source": "ctx._source.price = params.price",
    "params": { "price": 100.0 }
  },
  "upsert": {
    "id": 7,: "新文档",
    "price": 100.0
  }
}

2 乐观锁控制

# 使用version控制并发更新
PUT /my_index/_doc/1?version=2
{
  "id": 1,: "更新文档",
  "price": 199.0
}
# 使用if_seq_no和if_primary_term
POST /my_index/_update/1?if_seq_no=5&if_primary_term=1
{
  "doc": {
    "price": 299.0
  }
}

这些案例涵盖了Elasticsearch文档的基本CRUD操作,适用于日常开发中最常见的场景,如有特定需求,可以根据实际业务进行调整。

抱歉,评论功能暂时关闭!