【发布时间】:2016-05-16 02:03:40
【问题描述】:
编辑: This is basically what I want to do, only in Java
使用 ElasticSearch,我们将文档添加到索引,绕过 IndexRequest 项到 BulkRequestBuilder。
我希望在经过一段时间后从索引中删除文档(生存时间/ttl)
这可以通过为索引设置默认值或基于每个文档来完成。 两种方法我都可以。
下面的代码是对每个文档的尝试。这没用。我认为这是因为没有为索引启用 TTL。 要么告诉我我需要添加什么 Java 代码来启用 TTL 以便下面的代码工作,要么告诉我启用 TTL 的不同代码 + 为 Java 中的索引设置默认 TTL 值 我知道 how to do it from the REST API 但是如果可能的话,我需要从 Java 代码中完成。
logger.debug("Indexing record ({}): {}", id, map);
final IndexRequest indexRequest = new IndexRequest(_indexName, _documentType, id);
final long debug = indexRequest.ttl();
if (_ttl > 0) {
indexRequest.ttl(_ttl);
System.out.println("Setting TTL to " + _ttl);
System.out.println("IndexRequest now has ttl of " + indexRequest.ttl());
}
indexRequest.source(map);
indexRequest.operationThreaded(false);
bulkRequestBuilder.add(indexRequest);
}
// execute and block until done.
BulkResponse response;
try {
response = bulkRequestBuilder.execute().actionGet();
稍后我通过轮询此方法来检查我的单元测试,但文档计数从未下降。
public long getDocumentCount() throws Exception {
Client client = getClient();
try {
client.admin().indices().refresh(new RefreshRequest(INDEX_NAME)).actionGet();
ActionFuture<CountResponse> response = client.count(new CountRequest(INDEX_NAME).types(DOCUMENT_TYPE));
CountResponse countResponse = response.get();
return countResponse.getCount();
} finally {
client.close();
}
}
【问题讨论】:
-
您的意思是您想通过Java API 为您的文档设置
_ttl?这与为索引设置_ttl不同。您是否在映射中启用了_ttl字段? -
现在我认为我的挑战是为索引启用 _ttl 字段。我显然可以为文档设置它 - 这就是我在上面所做的,对吧? - 但它不会被清除。
-
我已更新问题以使我的问题更加清晰。
-
正如我所说,您需要在映射中使用enable
_ttl,因为默认情况下它是禁用的。之后,您可以将_ttl字段添加到您的文档中,它们应该会被清除。 -
是的。我如何通过 Java API 做到这一点?
标签: elasticsearch elasticsearch-bulk-api