0

I know how to get an alias if any given an index name in ElasticSearch:

es.indices.get_alias(indexname)

Is there a way to go the other way around? Something like es.indices.get_index(aliasname)? I implemented a workaround using the es.indices.get_alias for now but I am just curious.

2 Answers 2

3

I couldn't find any API returning an alias given an index name. Like I said, I had a workaround in Python using Elasticsearch module:

def get_alias_behind_index(client, indexname):
    if client.indices.exists_alias(name=indexname):
        return (list(client.indices.get_alias(indexname).keys())[0])
    return None
Sign up to request clarification or add additional context in comments.

Comments

0

Notice that a single alias may point to multiple indexes, so I'm assuming you want all the indexes behind that alias.

The only way I know is to:

  1. list all aliases metadata
  2. and iterate the aliases looking for the records related to the alias you are interested

Here is how I'll do it:

from opensearchpy import OpenSearch


# Get Client
# Use your own credentials and settings according to your opensearch
HOST = 'localhost'
PORT = 9200
AUTH = ('admin', 'admin')

client = OpenSearch(
    hosts=[{'host': HOST, 'port': PORT}],
    http_auth=AUTH,
    use_ssl=True,
    verify_certs=False)

def find_index_behind_alias(alias_name):
    """Find the index behind an alias.

    Parameters
    ----------
    alias_name : str
        The alias name.

    Returns
    -------
    index_names : list
        The index names behind the alias (return an empty list if the
        alias does not exist).
    """
    # 1) Get all aliases
    all_aliases = client.cat.aliases(
        name=['*'],
        format='json')

    # 2) Iterate looking for your targeted index
    alias_exist, index_names = False, []
    for alias in all_aliases:
        if alias['alias'] == alias_name:
            alias_exist = True
            index_names.append(alias['index'])
    
    if not alias_exist:
        print('Alias does not exist')
            
    return index_names

find_index_behind_alias(alias_name='my_alias_name')

Note: Use the parameter name to restrict what the client.cat.aliases returns (and update the code accordingly) if you do not want to list all the aliases with the aim to optimize the execution time of that loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.