我有以下集成测试:
public class TestElasticIT extends ESIntegTestCase {
private static final String esIndex = "test";
private static final String esEntityType = "entity";
private static final String esDetailType = "details";
private Client client = null;
@Before
public void beforeTests() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject(esEntityType).endObject().endObject();
XContentBuilder xContentBuilder2 = XContentFactory.jsonBuilder().startObject().startObject(esDetailType).startObject("_parent").field("type", esEntityType).endObject().endObject().endObject();
client = ESIntegTestCase.client();
createIndex(esIndex);
client.admin().indices().preparePutMapping(esIndex).setType(esDetailType).setSource(xContentBuilder2).get();
client.admin().indices().preparePutMapping(esIndex).setType(esEntityType).setSource(xContentBuilder).get();
}
@Test
public void testCreateAndRead() throws Exception {
ensureGreen(esIndex);
IndexResponse entityResponse = client.prepareIndex(esIndex, esEntityType).setSource(testJson).get(); //This could be any key/value json
IndexResponse detailResponse = client.prepareIndex(esIndex, esDetailType).setSource(testJsonDetail).setParent(entityResponse.getId()).get();
//I want to see both parent and child here
System.out.println(client.prepareSearch().execute().actionGet());
}
}
我遇到的问题是client.prepareSearch().execute().actionGet()
,我每隔一段时间才会返回testJson
。有时它会起作用,但大多数时候它只会返回任何东西。我怎样才能让我的集成测试每次都通过?
编辑: 有时有效且无效的查询:
client.prepareGet().setIndex(esIndex).setId(detailResponse.getId()).get();
client.prepareGet().setIndex(esIndex).setType(esDetailType).setRouting(esEntityType).setId(detailResponse.getId()).get();
答案 0 :(得分:1)
这是竞争条件,可能是因为您在创建索引后没有调用refresh(),而是在运行搜索请求之前依赖ES进行更新。
由于您的类扩展了ESIntegTestCase,您应该可以执行类似
的操作Timber::getContext()
有关此方法在测试API中的更多信息,请参阅以下链接: https://www.elastic.co/guide/en/elasticsearch/reference/current/integration-tests.html https://github.com/elastic/elasticsearch/blob/master/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java#L1186
这也可以在主(非测试)Java API中使用,如下所示:
this.refresh(esIndex);
有关Java API可用性的更多信息,请参见此处: https://static.javadoc.io/org.elasticsearch/elasticsearch/2.3.0/org/elasticsearch/client/IndicesAdminClient.html#refresh(org.elasticsearch.action.admin.indices.refresh.RefreshRequest)
编辑:
我在上面提供的第一个代码段仅适用于Elasticsearch 5.0 Alpha。在当前版本中,refresh方法不带参数: https://github.com/elastic/elasticsearch/blob/v2.4.0/core/src/test/java/org/elasticsearch/test/ESIntegTestCase.java