Skip to content

Commit

Permalink
[wpmlbridge-300] Cache cluster indices.
Browse files Browse the repository at this point in the history
- Avoid multiple checks on index name existance on multiple processes.

#48
  • Loading branch information
decodekult committed Jul 4, 2024
1 parent b5c29ef commit 5abcf62
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
40 changes: 39 additions & 1 deletion src/Manager/Indices.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ class Indices {
/** @var string|null */
private $stopwordFilterSlug = null;

/** @var string[]|null */
private static $clusterIndices = null;

/**
* @param Elasticsearch $elasticsearch
* @param Indexables $indexables
Expand Down Expand Up @@ -90,13 +93,46 @@ public function clearCurrentIndexLanguage() {
$this->currentIndexLanguage = '';
}

/**
* @return string[]
*/
private function getClusterIndicesCache() {
if ( null === self::$clusterIndices ) {
$clusterIndices = $this->elasticsearch->get_cluster_indices();
self::$clusterIndices = wp_list_pluck( $clusterIndices, 'index' );
}

return self::$clusterIndices;
}

/**
* @param string $indexName
*/
private function saveIndexInClusterCache( $indexName ) {
if ( null === self::$clusterIndices ) {
self::$clusterIndices = [];
}

if ( in_array( $indexName, self::$clusterIndices, true ) ) {
return;
}

self::$clusterIndices[] = $indexName;
}

private function clearClusterIndicesCache() {
self::$clusterIndices = null;
}

/**
* @param string $indexName
*
* @return bool
*/
public function indexExists( $indexName ) {
return $this->elasticsearch->index_exists( $indexName );
$clusterIndices = $this->getClusterIndicesCache();

return in_array( $indexName, $clusterIndices, true );
}

/**
Expand Down Expand Up @@ -155,6 +191,7 @@ public function generateIndexByIndexable( $indexable ) {
];

$this->elasticsearch->put_mapping( $indexName, $mapping );
$this->saveIndexInClusterCache( $indexName );
}

/**
Expand All @@ -168,6 +205,7 @@ public function generateIndexableIndexes( $indexables ) {

public function clearAllIndices() {
$this->elasticsearch->delete_all_indices();
$this->clearClusterIndicesCache();
}

public function generateMissingIndices() {
Expand Down
10 changes: 10 additions & 0 deletions tests/phpstan/stubs/elasticpress.stub
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ namespace ElasticPress {
*/
public function put_mapping( $index, $mapping, $return_type = 'bool' ) {}

/**
* @return string[]
*/
public function get_cluster_indices() {}

/**
* @return boolean
*/
Expand Down Expand Up @@ -160,6 +165,11 @@ namespace ElasticPress {
*/
public function get_index_name( $blog_id = null ) {}

/**
* @return array
*/
public function get_indexable_post_status() {}

/**
* @return array
*/
Expand Down

0 comments on commit 5abcf62

Please sign in to comment.