> ## Documentation Index
> Fetch the complete documentation index at: https://docs.omophub.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Batch Hierarchy Queries

> Run multiple OMOP concept hierarchy lookups in a single batched request to efficiently retrieve ancestors and descendants for bulk ETL workflows.

## Overview

This endpoint allows you to perform multiple hierarchy queries (ancestors, descendants, or full hierarchy) for multiple concepts in a single API call. This is highly efficient for applications that need hierarchical information for many concepts simultaneously.

## Request Body

<ParamField body="queries" type="array" required>
  Array of hierarchy query requests (1-100 queries)

  <Expandable title="queries">
    <ParamField body="query_id" type="string" required>
      Unique identifier for this query (used to match results)
    </ParamField>

    <ParamField body="concept_id" type="integer" required>
      The OMOP concept ID to query hierarchy for
    </ParamField>

    <ParamField body="operation" type="string" required>
      Type of hierarchy query. Options: `ancestors`, `descendants`, `hierarchy`, `level`, `relationships`, `related`, `traverse`
    </ParamField>

    <ParamField body="params" type="object">
      Optional parameters for the query

      <Expandable title="params">
        <ParamField body="max_levels" type="integer" default="10">
          Maximum number of hierarchy levels to traverse
        </ParamField>

        <ParamField body="relationship_types" type="array">
          Array of relationship types to follow (default: \["Is a"])
        </ParamField>

        <ParamField body="vocabulary_ids" type="array">
          Limit results to specific vocabularies
        </ParamField>

        <ParamField body="domain_ids" type="array">
          Limit results to specific domains
        </ParamField>

        <ParamField body="include_invalid" type="boolean" default="true">
          Include relationships to invalid/deprecated concepts
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

## Query Parameters

<ParamField query="vocab_release" type="string">
  Specific vocabulary release version (e.g., "2025.1")
</ParamField>

## Response

<ResponseField name="success" type="boolean" required>
  Indicates whether the request was successful
</ResponseField>

<ResponseField name="data" type="object" required>
  Response data containing batch results

  <Expandable title="data">
    <ResponseField name="results" type="array" required>
      Array of query results matching the input order

      <Expandable title="results">
        <ResponseField name="query_id" type="string">
          The query identifier from the request
        </ResponseField>

        <ResponseField name="concept_id" type="integer">
          The concept ID that was queried
        </ResponseField>

        <ResponseField name="operation" type="string">
          The operation that was performed
        </ResponseField>

        <ResponseField name="success" type="boolean">
          Whether this individual query succeeded
        </ResponseField>

        <ResponseField name="data" type="object">
          Result data if the query succeeded (structure varies by operation)

          <Expandable title="data (ancestors/descendants)">
            <ResponseField name="ancestors" type="array">
              Array of ancestor concepts (for ancestors/hierarchy operations)

              <Expandable title="concept object">
                <ResponseField name="concept_id" type="integer">
                  OMOP concept ID
                </ResponseField>

                <ResponseField name="concept_name" type="string">
                  Primary concept name
                </ResponseField>

                <ResponseField name="vocabulary_id" type="string">
                  Source vocabulary identifier
                </ResponseField>

                <ResponseField name="domain_id" type="string">
                  Clinical domain classification
                </ResponseField>

                <ResponseField name="concept_class_id" type="string">
                  Concept class identifier
                </ResponseField>

                <ResponseField name="standard_concept" type="string|null">
                  Standard concept flag (S, C, or null)
                </ResponseField>

                <ResponseField name="level" type="integer">
                  Distance from the source concept in hierarchy
                </ResponseField>
              </Expandable>
            </ResponseField>

            <ResponseField name="descendants" type="array">
              Array of descendant concepts (for descendants/hierarchy operations)

              <Expandable title="concept object">
                <ResponseField name="concept_id" type="integer">
                  OMOP concept ID
                </ResponseField>

                <ResponseField name="concept_name" type="string">
                  Primary concept name
                </ResponseField>

                <ResponseField name="vocabulary_id" type="string">
                  Source vocabulary identifier
                </ResponseField>

                <ResponseField name="domain_id" type="string">
                  Clinical domain classification
                </ResponseField>

                <ResponseField name="concept_class_id" type="string">
                  Concept class identifier
                </ResponseField>

                <ResponseField name="standard_concept" type="string|null">
                  Standard concept flag (S, C, or null)
                </ResponseField>

                <ResponseField name="level" type="integer">
                  Distance from the source concept in hierarchy
                </ResponseField>
              </Expandable>
            </ResponseField>

            <ResponseField name="total_count" type="integer">
              Total number of results
            </ResponseField>
          </Expandable>
        </ResponseField>

        <ResponseField name="error" type="string">
          Error message if the query failed
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="meta" type="object" required>
  Response metadata

  <Expandable title="meta">
    <ResponseField name="request_id" type="string">
      Unique request identifier
    </ResponseField>

    <ResponseField name="timestamp" type="string">
      ISO 8601 timestamp
    </ResponseField>

    <ResponseField name="vocab_release" type="string">
      Vocabulary release version used
    </ResponseField>
  </Expandable>
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.omophub.com/v1/concepts/hierarchy/batch" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "queries": [
        {
          "query_id": "q1",
          "concept_id": 201826,
          "operation": "ancestors",
          "params": {
            "max_levels": 5
          }
        },
        {
          "query_id": "q2",
          "concept_id": 4182210,
          "operation": "descendants",
          "params": {
            "max_levels": 3
          }
        },
        {
          "query_id": "q3",
          "concept_id": 313217,
          "operation": "hierarchy",
          "params": {
            "max_levels": 4,
            "relationship_types": ["Is a"]
          }
        }
      ]
    }'
  ```

  ```python Python theme={null}
  import requests

  def batch_hierarchy_query(queries, api_key):
      url = "https://api.omophub.com/v1/concepts/hierarchy/batch"
      headers = {
          "Authorization": f"Bearer {api_key}",
          "Content-Type": "application/json"
      }
      data = {"queries": queries}

      response = requests.post(url, json=data, headers=headers)
      return response.json()

  # Example usage
  queries = [
      {
          "query_id": "diabetes",
          "concept_id": 201826,
          "operation": "ancestors",
          "params": {"max_levels": 5}
      },
      {
          "query_id": "hypertension",
          "concept_id": 4182210,
          "operation": "descendants",
          "params": {"max_levels": 3}
      },
      {
          "query_id": "afib",
          "concept_id": 313217,
          "operation": "hierarchy",
          "params": {"max_levels": 4}
      }
  ]

  result = batch_hierarchy_query(queries, "YOUR_API_KEY")

  for query_result in result['data']['results']:
      if query_result['success']:
          data = query_result['data']
          ancestors = len(data.get('ancestors', []))
          descendants = len(data.get('descendants', []))
          print(f"{query_result['query_id']}: {ancestors} ancestors, {descendants} descendants")
      else:
          print(f"{query_result['query_id']}: Error - {query_result['error']}")
  ```

  ```javascript JavaScript theme={null}
  const batchHierarchyQuery = async (queries) => {
    const response = await fetch('https://api.omophub.com/v1/concepts/hierarchy/batch', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ queries })
    });

    return response.json();
  };

  // Example usage
  const queries = [
    { query_id: 'q1', concept_id: 201826, operation: 'ancestors', params: { max_levels: 5 } },
    { query_id: 'q2', concept_id: 4182210, operation: 'descendants', params: { max_levels: 3 } },
    { query_id: 'q3', concept_id: 313217, operation: 'hierarchy', params: { max_levels: 4 } }
  ];

  const result = await batchHierarchyQuery(queries);

  result.data.results.forEach((queryResult) => {
    if (queryResult.success) {
      const ancestors = queryResult.data.ancestors?.length || 0;
      const descendants = queryResult.data.descendants?.length || 0;
      console.log(`${queryResult.query_id}: ${ancestors} ancestors, ${descendants} descendants`);
    } else {
      console.error(`${queryResult.query_id} failed: ${queryResult.error}`);
    }
  });
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "data": {
      "results": [
        {
          "query_id": "q1",
          "concept_id": 201826,
          "operation": "ancestors",
          "success": true,
          "data": {
            "ancestors": [
              {
                "concept_id": 73211009,
                "concept_name": "Diabetes mellitus",
                "vocabulary_id": "SNOMED",
                "domain_id": "Condition",
                "concept_class_id": "Clinical Finding",
                "standard_concept": "S",
                "level": 1
              },
              {
                "concept_id": 64572001,
                "concept_name": "Disease",
                "vocabulary_id": "SNOMED",
                "domain_id": "Condition",
                "concept_class_id": "Clinical Finding",
                "standard_concept": "S",
                "level": 2
              }
            ],
            "total_count": 2
          }
        },
        {
          "query_id": "q2",
          "concept_id": 4182210,
          "operation": "descendants",
          "success": true,
          "data": {
            "descendants": [
              {
                "concept_id": 320128,
                "concept_name": "Essential hypertension",
                "vocabulary_id": "SNOMED",
                "domain_id": "Condition",
                "concept_class_id": "Clinical Finding",
                "standard_concept": "S",
                "level": 1
              }
            ],
            "total_count": 1
          }
        },
        {
          "query_id": "q3",
          "concept_id": 313217,
          "operation": "hierarchy",
          "success": true,
          "data": {
            "ancestors": [
              {
                "concept_id": 49436004,
                "concept_name": "Atrial fibrillation and flutter",
                "vocabulary_id": "SNOMED",
                "domain_id": "Condition",
                "concept_class_id": "Clinical Finding",
                "standard_concept": "S",
                "level": 1
              }
            ],
            "descendants": [],
            "total_count": 1
          }
        }
      ]
    },
    "meta": {
      "request_id": "req_batch_hierarchy_123",
      "timestamp": "2024-12-22T10:00:00Z",
      "vocab_release": "2025.1"
    }
  }
  ```
</ResponseExample>

## Usage Examples

### Simple Batch Ancestors

Get ancestors for multiple concepts:

```json theme={null}
{
  "queries": [
    {"query_id": "q1", "concept_id": 201826, "operation": "ancestors"},
    {"query_id": "q2", "concept_id": 4182210, "operation": "ancestors"},
    {"query_id": "q3", "concept_id": 313217, "operation": "ancestors"}
  ]
}
```

### Mixed Operations

Combine different operations in one batch:

```json theme={null}
{
  "queries": [
    {"query_id": "ancestors_query", "concept_id": 201826, "operation": "ancestors", "params": {"max_levels": 5}},
    {"query_id": "descendants_query", "concept_id": 4182210, "operation": "descendants", "params": {"max_levels": 3}},
    {"query_id": "full_hierarchy", "concept_id": 313217, "operation": "hierarchy", "params": {"max_levels": 4}}
  ]
}
```

### With Filtering

Use vocabulary and relationship filters:

```json theme={null}
{
  "queries": [
    {
      "query_id": "filtered_query",
      "concept_id": 201826,
      "operation": "hierarchy",
      "params": {
        "max_levels": 5,
        "relationship_types": ["Is a"],
        "vocabulary_ids": ["SNOMED", "ICD10CM"]
      }
    }
  ]
}
```

## Important Notes

* **Batch size limit**: Maximum 100 queries per batch request
* **Performance optimization**: Batch processing is significantly faster than individual requests
* **Error handling**: Individual query failures don't affect other queries in the batch
* **Result matching**: Use `query_id` to match results to your input queries
* **Rate limiting**: Batch requests count as single requests for rate limiting purposes

## Related Endpoints

* [Get Concept Ancestors](/api-reference/concepts/get-concept-ancestors) - Single concept ancestors
* [Get Concept Descendants](/api-reference/concepts/get-concept-descendants) - Single concept descendants
* [Get Concept Hierarchy](/api-reference/concepts/get-concept-hierarchy) - Complete hierarchy tree
