gpt4 book ai didi

elasticsearch - spring-data-elasticsearch 和更新

转载 作者:行者123 更新时间:2023-12-02 22:10:51 25 4
gpt4 key购买 nike

我正在使用 spring-data-elasticsearch 进行 CRUD 操作。

我有一个扩展 ElasticsearchRepository 的自定义存储库。

最终 ElasticsearchRepository 扩展了 CrudRepository 这意味着更新现有记录是可能的。

问题是,你如何做到这一点?我还没有找到一个叫做“update()”的方法

我认为执行以下操作会起作用(从 https://github.com/BioMedCentralLtd/spring-data-elasticsearch-sample-application 窃取的代码)

    //create
Book book = new Book();
book.setId("123455");
book.setName("Spring Data Elasticsearch");
book.setVersion(System.currentTimeMillis());
repository.save(book);

//update
book.setName("THIS IS A COMPLETELY NEW TITLE");
repository.save(book);

但是,第二次保存会引发 InvocationTargetException

用调试器检查它显示:
[book][0] [book][123455]: version conflict, current [1447792071681], provided [1447792071681]

Book 对象如下所示:
@Document(indexName = "book",type = "book" , shards = 1, replicas = 0, indexStoreType = "memory", refreshInterval = "-1")
public class Book {

@Id
private String id;
private String name;
private Long price;
@Version
private Long version;

public Map<Integer, Collection<String>> getBuckets() {
return buckets;
}

public void setBuckets(Map<Integer, Collection<String>> buckets) {
this.buckets = buckets;
}

@Field(type = FieldType.Nested)
private Map<Integer, Collection<String>> buckets = new HashMap();

public Book(){}

public Book(String id, String name,Long version) {
this.id = id;
this.name = name;
this.version = version;
}

getters and setters removed for space

}

我的 Repository 代码更简单:
import org.springframework.data.elasticsearch.entities.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface BookRepository extends ElasticsearchRepository<Book, Long> {

}

我必须提供更新方法吗?

编辑:

没关系。我将更新更改为:
    //update
book.setName("THIS IS A COMPLETELY NEW TITLE");
book.setVersion(System.currentTimeMillis());
repository.save(book);

它更新了记录。

最佳答案

您可以使用 UpdateQuery 和 ElasticSearchTemplate 来更新任何部分文档。例如

    final UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(mainIndexName);
updateRequest.type(typeName);
updateRequest.id(id);
updateRequest.doc(XContentFactory.jsonBuilder().startObject()
.field("accountType", accountType)
.endObject());
final UpdateQuery updateQuery = new UpdateQueryBuilder().withId(id)
.withClass(<DocumentClass>).withUpdateRequest(updateRequest).build();
UpdateResponse updateResponse = elasticSearchTemplate.update(updateQuery);

关于elasticsearch - spring-data-elasticsearch 和更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33766485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com