等到弹性搜索索引填满

时间:2017-10-26 08:31:52

标签: php elasticsearch

我想为与elasticsearch的通信编写集成测试。我的想法是在setUp方法中推送一些记录,然后让测试发出一些请求。我使用Elastica框架的初始化如下所示:

protected function setUp() {
  parent::setUp();

  $this->setApplicationConfig([
    'modules' => [
    ],
    'module_listener_options' => [
      'config_static_paths' => [
        'module/MyModule/tests/resources/config/elasticsearch.yaml',
      ],
      'check_dependencies' => true,
    ]
  ]);
  $this->getApplicationServiceLocator()
    ->setFactory('MyNamespace\ElasticSearchClient', 'MyNamespace\ElasticSearch\ClientFactory');

  self::$indexName = strtolower(uniqid('PHPUnit_'));
  self::$searchClient = $this->getApplicationServiceLocator()->get('\MyNamespace\ElasticSearchClient');
  $this->articleIdList = [
    'even' => [],
    'odd' => [],
  ];

  $searchIndex = new Index(self::$searchClient->getClient(), self::$indexName);
  $searchIndex->create();

  $documentCount = 1000;
  $searchDocumentBulk = new Bulk(self::$searchClient->getClient());
  $searchDocumentBulk->setIndex($searchIndex);
  for ($id = 1; $id <= $documentCount; $id++) {
    $article = [
      'client' => 'test',
      'content' => 'PHPUnit Test Text ' . ($id % 2 === 0 ? 'even' : 'odd') . ' ' . $id,
    ];
    $searchDocumentBulk->addDocument(new ElasticaDocument($id, $article, 'PHPUnit_Article'));
    $this->articleIdList[($id % 2 === 0 ? 'even' : 'odd')][] = $id;
  }
  $response = $searchDocumentBulk->send();
  $this->assertEquals($documentCount, $response->count());
}

由于结果计数不同,我的所有测试都失败了。我认为这样做的原因是记录被异步推送到服务器并且我的测试开始变快,所以此时并非所有文档都被编入索引。
但是我发现没有可能等到创建索引并且索引所有文档。

1 个答案:

答案 0 :(得分:0)

您是否只是在设置之后和实际测试之前运行sleep(5000)之类的内容? Elasticsearch可能需要一些时间来索引文档。