Elasticsearch文档增删改查操作

wen java案例 1

本文目录导读:

Elasticsearch文档增删改查操作

  1. 索引(Index)操作
  2. 创建文档(Create)
  3. 查询文档(Read)
  4. 更新文档(Update)
  5. 删除文档(Delete)
  6. 批量操作(Bulk API)
  7. Mget批量查询
  8. 高级查询示例
  9. 使用Java API示例
  10. 注意事项

我来详细介绍Elasticsearch的文档增删改查(CRUD)操作。

索引(Index)操作

创建索引

PUT /my_index
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 2
  },
  "mappings": {
    "properties": {
      "title": { "type": "text" },
      "content": { "type": "text" },
      "price": { "type": "double" },
      "created_at": { "type": "date" }
    }
  }
}

查看索引

GET /my_index
GET _cat/indices?v

删除索引

DELETE /my_index

创建文档(Create)

自动生成ID

POST /my_index/_doc
{: "Elasticsearch入门教程",
  "content": "这是关于ES的基础教程",
  "price": 29.9,
  "created_at": "2024-01-15"
}

指定ID

PUT /my_index/_doc/1
{: "Spring Boot实战",
  "content": "Spring Boot开发指南",
  "price": 49.9,
  "created_at": "2024-01-16"
}

使用_create(确保唯一)

PUT /my_index/_create/2
{: "Java编程思想",
  "content": "Java经典书籍",
  "price": 89.9
}

查询文档(Read)

根据ID查询

GET /my_index/_doc/1

查询所有文档

GET /my_index/_search
{
  "query": {
    "match_all": {}
  }
}

条件查询

GET /my_index/_search
{
  "query": {
    "match": {
      "title": "Spring"
    }
  }
}

复合查询

GET /my_index/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "Java" } }
      ],
      "filter": [
        { "range": { "price": { "gte": 50 } } }
      ]
    }
  }
}

更新文档(Update)

部分更新

POST /my_index/_update/1
{
  "doc": {
    "price": 39.9,
    "tags": ["Java", "Spring"]
  }
}

使用脚本更新

POST /my_index/_update/1
{
  "script": {
    "source": "ctx._source.price += params.increase",
    "params": {
      "increase": 10
    }
  }
}

完全替换(使用Index API)

PUT /my_index/_doc/1
{: "Spring Boot实战(第二版)",
  "content": "完全重写的内容",
  "price": 59.9,
  "created_at": "2024-02-01"
}

条件更新(通过更新API)

POST /my_index/_update_by_query
{
  "script": {
    "source": "ctx._source.price = ctx._source.price * 0.8"
  },
  "query": {
    "term": {
      "title": "Java"
    }
  }
}

删除文档(Delete)

根据ID删除

DELETE /my_index/_doc/1

条件删除

POST /my_index/_delete_by_query
{
  "query": {
    "match": {
      "price": 29.9
    }
  }
}

删除所有文档

POST /my_index/_delete_by_query
{
  "query": {
    "match_all": {}
  }
}

批量操作(Bulk API)

批量创建/更新

POST /_bulk
{"index": {"_index": "my_index", "_id": "3"}}: "Python基础", "price": 39.9}
{"index": {"_index": "my_index", "_id": "4"}}: "Node.js进阶", "price": 45.9}

批量混合操作

POST /my_index/_bulk
{"index": {"_id": "5"}}: "Redis实战", "price": 35.9}
{"update": {"_id": "1"}}
{"doc": {"price": 29.9}}
{"delete": {"_id": "2"}}

Mget批量查询

GET /my_index/_mget
{
  "ids": ["1", "3", "5"]
}

高级查询示例

分页查询

GET /my_index/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "match_all": {}
  },
  "sort": [
    { "price": { "order": "desc" } }
  ]
}

聚合查询

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "avg_price": {
      "avg": { "field": "price" }
    }
  }
}

使用Java API示例

添加依赖

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

基本操作代码

@SpringBootTest
public class EsCrudTest {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
    // 创建文档
    @Test
    public void testCreate() {
        Product product = new Product();
        product.setId("1");
        product.setTitle("Spring Boot实战");
        product.setPrice(49.9);
        IndexQuery indexQuery = new IndexQueryBuilder()
            .withId(product.getId())
            .withObject(product)
            .build();
        String index = elasticsearchTemplate.index(indexQuery, IndexCoordinates.of("my_index"));
        System.out.println("创建成功,索引ID: " + index);
    }
    // 查询文档
    @Test
    public void testQuery() {
        GetQuery getQuery = new GetQuery("1");
        Product product = elasticsearchTemplate
            .query(getQuery, GetResponse.class, IndexCoordinates.of("my_index"));
    }
    // 更新文档
    @Test
    public void testUpdate() {
        UpdateQuery updateQuery = UpdateQuery.builder("1")
            .withDocument(JsonData.of(Map.of("price", 39.9)))
            .build();
        UpdateResponse response = elasticsearchTemplate
            .update(updateQuery, IndexCoordinates.of("my_index"));
    }
    // 删除文档
    @Test
    public void testDelete() {
        String delete = elasticsearchTemplate
            .delete("1", IndexCoordinates.of("my_index"));
    }
}

注意事项

  1. 幂等性:PUT方式创建文档是幂等的,POST不是
  2. 版本控制:ES使用版本号控制并发更新
  3. 实时性:ES是近实时系统,新增文档需要刷新后才能搜索到
  4. 数据一致性:更新操作是原子的,但读取可能不是实时的

这些是ES文档操作的核心内容,根据实际需求选择合适的方式。

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