Skip to content

Commit e7152a1

Browse files
author
Nik Everett
committed
Improve performance of Status->getIndicesWithAlias
Particularly improves performance on clusters with many indices. Slow to instant. Closes ruflin#563
1 parent 2cb3a2c commit e7152a1

File tree

3 files changed

+26
-12
lines changed

3 files changed

+26
-12
lines changed

changes.txt

+2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
CHANGES
2+
2014-03-04
3+
- Improve performance of Elastica/Status->getIndicesWithAlias and aliasExists on clusters with many indices
24

35
2014-03-02
46
- Release v1.0.1.0

lib/Elastica/Status.php

+18-12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php
22

33
namespace Elastica;
4+
use Elastica\Exception\ResponseException;
45
use Elastica\Index\Status as IndexStatus;
56

67
/**
@@ -105,30 +106,35 @@ public function indexExists($name)
105106
*/
106107
public function aliasExists($name)
107108
{
108-
foreach ($this->getIndexStatuses() as $status) {
109-
if ($status->hasAlias($name)) {
110-
return true;
111-
}
112-
}
109+
return count($this->getIndicesWithAlias($name)) > 0;
113110

114111
return false;
115112
}
116113

117114
/**
118115
* Returns an array with all indices that the given alias name points to
119116
*
120-
* @param string $name Alias name
117+
* @param string $alias Alias name
121118
* @return array|\Elastica\Index[] List of Elastica\Index
122119
*/
123-
public function getIndicesWithAlias($name)
120+
public function getIndicesWithAlias($alias)
124121
{
125-
$indices = array();
126-
foreach ($this->getIndexStatuses() as $status) {
127-
if ($status->hasAlias($name)) {
128-
$indices[] = $status->getIndex();
122+
$response = null;
123+
try {
124+
$response = $this->_client->request("/_alias/$alias");
125+
} catch (ResponseException $e) {
126+
$transferInfo = $e->getResponse()->getTransferInfo();
127+
// 404 means the index alias doesn't exist which means no indexes have it.
128+
if ($transferInfo['http_code'] === 404) {
129+
return array();
129130
}
131+
// If we don't have a 404 then this is still unexpected so rethrow the exception.
132+
throw $e;
133+
}
134+
$indices = array();
135+
foreach ($response->getData() as $name => $unused) {
136+
$indices[] = new Index($this->_client, $name);
130137
}
131-
132138
return $indices;
133139
}
134140

test/lib/Elastica/Test/StatusTest.php

+6
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,12 @@ public function testAliasExists()
9090
$index1->addAlias($aliasName);
9191
$status->refresh();
9292
$this->assertTrue($status->aliasExists($aliasName));
93+
94+
$indicesWithAlias = $status->getIndicesWithAlias($aliasName);
95+
$this->assertEquals(array("elastica_$indexName"), array_map(
96+
function($index) {
97+
return $index->getName();
98+
}, $indicesWithAlias));
9399
}
94100

95101
public function testServerStatus()

0 commit comments

Comments
 (0)