Skip to content

Commit

Permalink
feat(clients): add helper to check if an index exists (#3646) (genera…
Browse files Browse the repository at this point in the history
…ted) [skip ci]

Co-authored-by: Pierre Millot <pierre.millot@algolia.com>
Co-authored-by: Thomas Raffray <Fluf22@users.noreply.github.com>
  • Loading branch information
3 people committed Sep 4, 2024
1 parent 3d02b31 commit c883383
Show file tree
Hide file tree
Showing 49 changed files with 1,253 additions and 92 deletions.
17 changes: 17 additions & 0 deletions clients/algoliasearch-client-go/algolia/search/api_search.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -6743,4 +6743,16 @@ public Duration getSecuredApiKeyRemainingValidity(@Nonnull String securedApiKey)

return Duration.ofSeconds(timeStamp - Instant.now().getEpochSecond());
}

public boolean indexExists(String indexName) {
try {
getSettings(indexName);
} catch (AlgoliaApiException e) {
if (e.getStatusCode() == 404) {
return false;
}
throw e;
}
return true;
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.

import { createAuth, createTransporter, getAlgoliaAgent, shuffle, createIterablePromise } from '@algolia/client-common';
import {
createAuth,
createTransporter,
getAlgoliaAgent,
shuffle,
ApiError,
createIterablePromise,
} from '@algolia/client-common';
import type {
CreateClientOptions,
Headers,
Host,
QueryParameters,
Request,
RequestOptions,
ApiError,
IterableOptions,
} from '@algolia/client-common';

Expand Down Expand Up @@ -643,6 +649,19 @@ export function createSearchClient({
return { copyOperationResponse, batchResponses, moveOperationResponse };
},

async indexExists({ indexName }: GetSettingsProps): Promise<boolean> {
try {
await this.getSettings({ indexName });
} catch (error) {
if (error instanceof ApiError && error.status === 404) {
return false;
}
throw error;
}

return true;
},

/**
* Helper: calls the `search` method but with certainty that we will only request Algolia records (hits) and not facets.
* Disclaimer: We don't assert that the parameters you pass to this method only contains `hits` requests to prevent impacting search performances, this helper is purely for typing purposes.
Expand Down Expand Up @@ -1045,7 +1064,6 @@ export function createSearchClient({
const requestPath = '/1/indexes/{indexName}/rules/clear'.replace('{indexName}', encodeURIComponent(indexName));
const headers: Headers = {};
const queryParameters: QueryParameters = {};

if (forwardToReplicas !== undefined) {
queryParameters.forwardToReplicas = forwardToReplicas.toString();
}
Expand Down Expand Up @@ -1082,7 +1100,6 @@ export function createSearchClient({
const requestPath = '/1/indexes/{indexName}/synonyms/clear'.replace('{indexName}', encodeURIComponent(indexName));
const headers: Headers = {};
const queryParameters: QueryParameters = {};

if (forwardToReplicas !== undefined) {
queryParameters.forwardToReplicas = forwardToReplicas.toString();
}
Expand Down Expand Up @@ -1454,6 +1471,7 @@ export function createSearchClient({
.replace('{objectID}', encodeURIComponent(objectID));
const headers: Headers = {};
const queryParameters: QueryParameters = {};

if (forwardToReplicas !== undefined) {
queryParameters.forwardToReplicas = forwardToReplicas.toString();
}
Expand Down Expand Up @@ -1595,7 +1613,6 @@ export function createSearchClient({
if (length !== undefined) {
queryParameters.length = length.toString();
}

if (indexName !== undefined) {
queryParameters.indexName = indexName.toString();
}
Expand Down Expand Up @@ -1642,6 +1659,7 @@ export function createSearchClient({
.replace('{objectID}', encodeURIComponent(objectID));
const headers: Headers = {};
const queryParameters: QueryParameters = {};

if (attributesToRetrieve !== undefined) {
queryParameters.attributesToRetrieve = attributesToRetrieve.toString();
}
Expand Down Expand Up @@ -2381,10 +2399,10 @@ export function createSearchClient({
const requestPath = '/1/indexes/{indexName}/rules/batch'.replace('{indexName}', encodeURIComponent(indexName));
const headers: Headers = {};
const queryParameters: QueryParameters = {};

if (forwardToReplicas !== undefined) {
queryParameters.forwardToReplicas = forwardToReplicas.toString();
}

if (clearExistingRules !== undefined) {
queryParameters.clearExistingRules = clearExistingRules.toString();
}
Expand Down Expand Up @@ -2487,7 +2505,6 @@ export function createSearchClient({
if (forwardToReplicas !== undefined) {
queryParameters.forwardToReplicas = forwardToReplicas.toString();
}

if (replaceExistingSynonyms !== undefined) {
queryParameters.replaceExistingSynonyms = replaceExistingSynonyms.toString();
}
Expand Down
14 changes: 14 additions & 0 deletions clients/algoliasearch-client-php/lib/Api/SearchClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Algolia\AlgoliaSearch\Algolia;
use Algolia\AlgoliaSearch\Configuration\SearchConfig;
use Algolia\AlgoliaSearch\Exceptions\ExceededRetriesException;
use Algolia\AlgoliaSearch\Exceptions\NotFoundException;
use Algolia\AlgoliaSearch\Exceptions\ValidUntilNotFoundException;
use Algolia\AlgoliaSearch\Iterators\ObjectIterator;
use Algolia\AlgoliaSearch\Iterators\RuleIterator;
Expand Down Expand Up @@ -3098,6 +3099,19 @@ public static function getSecuredApiKeyRemainingValidity($securedApiKey)
return $validUntil - time();
}

public function indexExists($indexName)
{
try {
$this->getSettings($indexName);
} catch (NotFoundException $e) {
return false;
} catch (Exception $e) {
throw $e;
}

return true;
}

private function sendRequest($method, $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions, $useReadTransporter = false)
{
if (!isset($requestOptions['headers'])) {
Expand Down
13 changes: 13 additions & 0 deletions clients/algoliasearch-client-python/algoliasearch/search/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,19 @@ async def _copy() -> UpdatedAtResponse:
move_operation_response=move_operation_response,
)

async def index_exists(self, index_name: str) -> bool:
"""
Helper: Checks if the given `index_name` exists.
"""
try:
await self.get_settings(index_name)
except Exception as e:
if isinstance(e, RequestException) and e.status_code == 404:
return False
raise e

return True

async def add_api_key_with_http_info(
self,
api_key: ApiKey,
Expand Down
12 changes: 12 additions & 0 deletions clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3532,5 +3532,17 @@ def replace_all_objects(index_name, objects, batch_size = 1000, request_options
move_operation_response: move_operation_response
)
end

def index_exists?(index_name)
begin
get_settings(index_name)
rescue AlgoliaHttpError => e
return false if e.code == 404

raise e
end

true
end
end
end
48 changes: 48 additions & 0 deletions snippets/csharp/src/Search.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1000,6 +1000,54 @@ public async Task SnippetForSearchClientHasPendingMappings()
// SEPARATOR<
}

/// <summary>
/// Snippet for the IndexExists method.
///
/// indexExists
/// </summary>
public async Task SnippetForSearchClientIndexExists()
{
// >SEPARATOR indexExists indexExists
// Initialize the client
var client = new SearchClient(new SearchConfig("YOUR_APP_ID", "YOUR_API_KEY"));

// Call the API
var response = await client.IndexExistsAsync("<YOUR_INDEX_NAME>");
// SEPARATOR<
}

/// <summary>
/// Snippet for the IndexExists method.
///
/// indexNotExists
/// </summary>
public async Task SnippetForSearchClientIndexExists1()
{
// >SEPARATOR indexExists indexNotExists
// Initialize the client
var client = new SearchClient(new SearchConfig("YOUR_APP_ID", "YOUR_API_KEY"));

// Call the API
var response = await client.IndexExistsAsync("<YOUR_INDEX_NAME>");
// SEPARATOR<
}

/// <summary>
/// Snippet for the IndexExists method.
///
/// indexExistsWithError
/// </summary>
public async Task SnippetForSearchClientIndexExists2()
{
// >SEPARATOR indexExists indexExistsWithError
// Initialize the client
var client = new SearchClient(new SearchConfig("YOUR_APP_ID", "YOUR_API_KEY"));

// Call the API
var response = await client.IndexExistsAsync("<YOUR_INDEX_NAME>");
// SEPARATOR<
}

/// <summary>
/// Snippet for the ListApiKeys method.
///
Expand Down
45 changes: 45 additions & 0 deletions snippets/dart/lib/search.dart
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,51 @@ void snippetForhasPendingMappings() async {
// SEPARATOR<
}

// Snippet for the indexExists method.
//
// indexExists
void snippetForindexExists() async {
// >SEPARATOR indexExists indexExists
// Initialize the client
final client = SearchClient(appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY');

// Call the API
final response = await client.indexExists(
indexName: "<YOUR_INDEX_NAME>",
);
// SEPARATOR<
}

// Snippet for the indexExists method.
//
// indexNotExists
void snippetForindexExists1() async {
// >SEPARATOR indexExists indexNotExists
// Initialize the client
final client = SearchClient(appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY');

// Call the API
final response = await client.indexExists(
indexName: "<YOUR_INDEX_NAME>",
);
// SEPARATOR<
}

// Snippet for the indexExists method.
//
// indexExistsWithError
void snippetForindexExists2() async {
// >SEPARATOR indexExists indexExistsWithError
// Initialize the client
final client = SearchClient(appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY');

// Call the API
final response = await client.indexExists(
indexName: "<YOUR_INDEX_NAME>",
);
// SEPARATOR<
}

// Snippet for the listApiKeys method.
//
// listApiKeys
Expand Down
Loading

0 comments on commit c883383

Please sign in to comment.