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

# Query

Searches for nearest neighbors in the encrypted index using vector similarity search. Supports single vector queries, batch queries, and semantic search with text content.

```go theme={null}
func (e *EncryptedIndex) Query(ctx context.Context, input QueryInput) (*QueryResponse, error)
```

### Parameters

| Parameter | Type                                          | Description                                 |
| --------- | --------------------------------------------- | ------------------------------------------- |
| `ctx`     | `context.Context`                             | Context for cancellation and timeouts       |
| `input`   | [`QueryInput`](../types#queryinput-interface) | Either `QueryParams` or `BinaryQueryParams` |

#### QueryParams

| Field               | Type                     | Description                                                                                                                                                                                                                                             |
| ------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `QueryVector`       | `[]float32`              | *(Optional)* Single query vector for similarity search                                                                                                                                                                                                  |
| `BatchQueryVectors` | `[][]float32`            | *(Optional)* Multiple query vectors for batch search                                                                                                                                                                                                    |
| `QueryContents`     | `*string`                | *(Optional)* Text content for semantic search                                                                                                                                                                                                           |
| `TopK`              | `int32`                  | *(Optional)* Number of nearest neighbors to return (default: 100)                                                                                                                                                                                       |
| `NProbes`           | `*int32`                 | *(Optional)* Number of clusters to probe for search                                                                                                                                                                                                     |
| `Filters`           | `map[string]interface{}` | *(Optional)* Metadata filters to apply                                                                                                                                                                                                                  |
| `Include`           | `[]string`               | *(Optional)* Fields to include in results: `"metadata"`, `"distance"`, `"vector"`. Defaults to `[]` (only `id` is returned). `QueryResultItem` has no `Contents` field — to retrieve contents, use [`Get`](./get) with the matching IDs after querying. |
| `Greedy`            | `*bool`                  | *(Optional)* Use greedy search algorithm                                                                                                                                                                                                                |
| `RerankMult`        | `*int32`                 | *(Optional)* Multiplier for stage 1 retrieval in reranking indexes. Stage 1 returns `TopK * RerankMult` candidates before reranking narrows to `TopK`. Server default: `10`. Ignored by indexes that do not rerank.                                     |

<Note>`Include` defaults differ between endpoints: `Query` returns `[]` (only `Id`) by default, while [`Get`](./get) returns `["vector", "contents", "metadata"]`.</Note>

### Returns

* `*QueryResponse`: Search results containing vectors, distances, and requested fields
* `error`: Any error encountered during the search operation

### Error Handling

<AccordionGroup>
  <Accordion title="API Errors">
    * Returns error if the API request fails due to network connectivity issues
    * Returns error if authentication fails (invalid API key)
    * Returns error if the encryption key is invalid for the specified index
    * Returns error if there are internal server errors during the search
  </Accordion>

  <Accordion title="Validation Errors">
    * Returns error if none of QueryVector, BatchQueryVectors, or QueryContents is provided
    * Returns error if vector dimensions don't match the index configuration
    * Returns error if parameter values are out of valid ranges
    * Returns error if the Include parameter contains invalid field names
  </Accordion>
</AccordionGroup>

### Example Usage

#### Single Vector Query

```go theme={null}
// Basic similarity search
queryVector := []float32{0.1, 0.2, 0.3, 0.4}
params := cyborgdb.QueryParams{
    QueryVector: queryVector,
    TopK:        5,
    Include:     []string{"distance", "metadata"},
}

results, err := index.Query(context.Background(), params)
if err != nil {
    log.Fatalf("Query failed: %v", err)
}

// QueryResponse.Results is a oneOf wrapper — single-vector queries populate
// ArrayOfQueryResultItem; batch queries populate ArrayOfArrayOfQueryResultItem.
if results.Results.ArrayOfQueryResultItem != nil {
    for i, result := range *results.Results.ArrayOfQueryResultItem {
        fmt.Printf("%d. ID: %s, Distance: %.4f\n", i+1, result.Id, result.GetDistance())
    }
}
```

#### Batch Vector Query

```go theme={null}
// Query multiple vectors at once
queryVectors := [][]float32{
    {0.1, 0.2, 0.3, 0.4},
    {0.5, 0.6, 0.7, 0.8},
    {0.9, 1.0, 1.1, 1.2},
}

params := cyborgdb.QueryParams{
    BatchQueryVectors: queryVectors,
    TopK:              3,
    Include:           []string{"metadata"},
}

batchResults, err := index.Query(context.Background(), params)
if err != nil {
    log.Fatalf("Batch query failed: %v", err)
}

// Batch queries populate ArrayOfArrayOfQueryResultItem ([][]QueryResultItem).
if batchResults.Results.ArrayOfArrayOfQueryResultItem != nil {
    resultSets := *batchResults.Results.ArrayOfArrayOfQueryResultItem
    fmt.Printf("Batch query returned %d result sets\n", len(resultSets))
    for i, set := range resultSets {
        fmt.Printf("Query %d: %d results\n", i+1, len(set))
    }
}
```

#### Semantic Search with Text

```go theme={null}
// Search using text content (requires embedding model configured on index)
textQuery := "machine learning healthcare applications"
params := cyborgdb.QueryParams{
    QueryContents: &textQuery,
    TopK:          10,
    Include:       []string{"metadata", "distance"},
}

results, err := index.Query(context.Background(), params)
if err != nil {
    log.Fatalf("Content search failed: %v", err)
}

if results.Results.ArrayOfQueryResultItem != nil {
    for i, result := range *results.Results.ArrayOfQueryResultItem {
        fmt.Printf("%d. ID: %s, Distance: %.4f\n", i+1, result.Id, result.GetDistance())
        if result.Metadata != nil {
            fmt.Printf("   Metadata: %v\n", result.Metadata)
        }
    }
}
```

<Tip>`BinaryQueryParams` is available as an alternative to `QueryParams` that uses binary transfer for large batch queries. This can significantly improve performance when querying with many vectors at once.</Tip>

<Note>`BinaryQueryParams` does **not** accept `RerankMult` — it is supported only on `QueryParams`. Use `QueryParams` if you need to tune the stage-1 candidate multiplier on a reranking index.</Note>
