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

# Rerank documents

> Rerank results according to their relevance to a query.

For guidance and examples, see [Rerank results](https://docs.pinecone.io/guides/search/rerank-results).

```python Python theme={null}
from pinecone.grpc import PineconeGRPC as Pinecone

pc = Pinecone(api_key="YOUR_API_KEY")

result = pc.inference.rerank(
    model="bge-reranker-v2-m3",
    query="The tech company Apple is known for its innovative products like the iPhone.",
    documents=[
        {"id": "vec1", "text": "Apple is a popular fruit known for its sweetness and crisp texture."},
        {"id": "vec2", "text": "Many people enjoy eating apples as a healthy snack."},
        {"id": "vec3", "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."},
        {"id": "vec4", "text": "An apple a day keeps the doctor away, as the saying goes."},
    ],
    top_n=4,
    return_documents=True,
    parameters={
        "truncate": "END"
    }
)

print(result)
```

```javascript JavaScript theme={null}
import { Pinecone } from '@pinecone-database/pinecone';

const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' });

const rerankingModel = 'bge-reranker-v2-m3';

const query = 'The tech company Apple is known for its innovative products like the iPhone.';

const documents = [
  { id: 'vec1', text: 'Apple is a popular fruit known for its sweetness and crisp texture.' },
  { id: 'vec2', text: 'Many people enjoy eating apples as a healthy snack.' },
  { id: 'vec3', text: 'Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.' },
  { id: 'vec4', text: 'An apple a day keeps the doctor away, as the saying goes.' },
];

const rerankOptions = {
  topN: 4,
  returnDocuments: true,
  parameters: {
    truncate: 'END'
  }, 
};

const response = await pc.inference.rerank(
  rerankingModel,
  query,
  documents,
  rerankOptions
);

console.log(response);
```

```java Java theme={null}
import io.pinecone.clients.Inference;
import io.pinecone.clients.Pinecone;
import org.openapitools.inference.client.model.RerankResult;
import org.openapitools.inference.client.ApiException;

import java.util.*;

public class RerankExample {
    public static void main(String[] args) throws ApiException {
        Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build();
        Inference inference = pc.getInferenceClient();

        // The model to use for reranking
        String model = "bge-reranker-v2-m3";

        // The query to rerank documents against
        String query = "The tech company Apple is known for its innovative products like the iPhone.";

        // Add the documents to rerank
        List<Map<String, Object>> documents = new ArrayList<>();
        Map<String, Object> doc1 = new HashMap<>();
        doc1.put("id", "vec1");
        doc1.put("text", "Apple is a popular fruit known for its sweetness and crisp texture.");
        documents.add(doc1);

        Map<String, Object> doc2 = new HashMap<>();
        doc2.put("id", "vec2");
        doc2.put("text", "Many people enjoy eating apples as a healthy snack.");
        documents.add(doc2);

        Map<String, Object> doc3 = new HashMap<>();
        doc3.put("id", "vec3");
        doc3.put("text", "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.");
        documents.add(doc3);

        Map<String, Object> doc4 = new HashMap<>();
        doc4.put("id", "vec4");
        doc4.put("text", "An apple a day keeps the doctor away, as the saying goes.");
        documents.add(doc4);

        // The fields to rank the documents by. If not provided, the default is "text"
        List<String> rankFields = Arrays.asList("text");

        // The number of results to return sorted by relevance. Defaults to the number of inputs
        int topN = 4;

        // Whether to return the documents in the response
        boolean returnDocuments = true;

        // Additional model-specific parameters for the reranker
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("truncate", "END");

        // Send ranking request
        RerankResult result = inference.rerank(model, query, documents, rankFields, topN, returnDocuments, parameters);

        // Get ranked data
        System.out.println(result.getData());
    }
}
```

```go Go theme={null}
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/pinecone-io/go-pinecone/v4/pinecone"
)

func main() {
    ctx := context.Background()

    pc, err := pinecone.NewClient(pinecone.NewClientParams{
        ApiKey: "YOUR_API_KEY",
    })
    if err != nil {
        log.Fatalf("Failed to create Client: %v", err)
    }

    rerankModel := "bge-reranker-v2-m3"
    topN := 4
    returnDocuments := true
    documents := []pinecone.Document{
        {"id": "vec1", "text": "Apple is a popular fruit known for its sweetness and crisp texture."},
        {"id": "vec2", "text": "Many people enjoy eating apples as a healthy snack."},
        {"id": "vec3", "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."},
        {"id": "vec4", "text": "An apple a day keeps the doctor away, as the saying goes."},
    }

    ranking, err := pc.Inference.Rerank(ctx, &pinecone.RerankRequest{
        Model:           rerankModel,
        Query:           "The tech company Apple is known for its innovative products like the iPhone.",
        ReturnDocuments: &returnDocuments,
        TopN:            &topN,
        RankFields:      &[]string{"text"},
        Documents:       documents,
    })
    if err != nil {
        log.Fatalf("Failed to rerank: %v", err)
    }
    fmt.Printf("Rerank result: %+v\n", ranking)
}
```

```csharp C# theme={null}
using Pinecone;

var pinecone = new PineconeClient("YOUR_API_KEY");

// The model to use for reranking
var model = "bge-reranker-v2-m3";

// The query to rerank documents against
var query = "The tech company Apple is known for its innovative products like the iPhone.";

// Add the documents to rerank
var documents = new List<Dictionary<string, object>>
{
    new()
    {
        ["id"] = "vec1",
        ["my_field"] = "Apple is a popular fruit known for its sweetness and crisp texture."
    },
    new()
    {
        ["id"] = "vec2",
        ["my_field"] = "Many people enjoy eating apples as a healthy snack."
    },
    new()
    {
        ["id"] = "vec3",
        ["my_field"] =
            "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."
    },
    new()
    {
        ["id"] = "vec4",
        ["my_field"] = "An apple a day keeps the doctor away, as the saying goes."
    }
};

// The fields to rank the documents by. If not provided, the default is "text"
var rankFields = new List<string> { "my_field" };

// The number of results to return sorted by relevance. Defaults to the number of inputs
int topN = 4;

// Whether to return the documents in the response
bool returnDocuments = true;

// Additional model-specific parameters for the reranker
var parameters = new Dictionary<string, object>
{
    ["truncate"] = "END"
};

// Send ranking request
var result = await pinecone.Inference.RerankAsync(
    new RerankRequest
    {
        Model = model,
        Query = query,
        Documents = documents,
        RankFields = rankFields,
        TopN = topN,
        ReturnDocuments = true,
        Parameters = parameters
    });

Console.WriteLine(result);
```

```shell curl theme={null}
PINECONE_API_KEY="YOUR_API_KEY"

curl https://api.pinecone.io/rerank \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "X-Pinecone-Api-Version: 2025-04" \
  -H "Api-Key: $PINECONE_API_KEY" \
-d '{
  "model": "bge-reranker-v2-m3",
  "query": "The tech company Apple is known for its innovative products like the iPhone.",
  "return_documents": true,
  "top_n": 4,
  "documents": [
    {"id": "vec1", "text": "Apple is a popular fruit known for its sweetness and crisp texture."},
    {"id": "vec2", "text": "Many people enjoy eating apples as a healthy snack."},
    {"id": "vec3", "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."},
    {"id": "vec4", "text": "An apple a day keeps the doctor away, as the saying goes."}
  ],
  "parameters": {
    "truncate": "END"
  }
}'
```

```python Python theme={null}
RerankResult(
  model='bge-reranker-v2-m3',
  data=[
    { "index": 2, "score": 0.48357219,
      "document": {"id": "vec3", "text": "Apple Inc. has re..."} },
    { "index": 0, "score": 0.048405956,
      "document": {"id": "vec1", "text": "Apple is a popula..."} },
    { "index": 3, "score": 0.007846239,
      "document": {"id": "vec4", "text": "An apple a day ke..."} },
    {"index": 1, "score": 0.0006563728,
      "document": {"id": "vec2", "text": "Many people enjoy..."}}
  ],
  usage={'rerank_units': 1}
)
```

```javascript JavaScript theme={null}
{
  "model": "bge-reranker-v2-m3",
  "data": [
    { "index": 2, "score": 0.48357219, "document": {} },
    { "index": 0, "score": 0.048405956, "document": {} },
    { "index": 3, "score": 0.007846239, "document": {} },
    { "index": 1, "score": 0.0006563728, "document": {} }
  ],
  "usage": { "rerankUnits": 1 }
}
```

```java Java theme={null}
[class RankedDocument {
    index: 2
    score: 0.48357219
    document: {id=vec3, text=Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces.}
    additionalProperties: null
}, class RankedDocument {
    index: 0
    score: 0.048405956
    document: {id=vec1, text=Apple is a popular fruit known for its sweetness and crisp texture.}
    additionalProperties: null
}, class RankedDocument {
    index: 3
    score: 0.007846239
    document: {id=vec4, text=An apple a day keeps the doctor away, as the saying goes.}
    additionalProperties: null
}, class RankedDocument {
    index: 1
    score: 0.0006563728
    document: {id=vec2, text=Many people enjoy eating apples as a healthy snack.}
    additionalProperties: null
}]
```

```go Go theme={null}
Rerank result: {
  "data": [
    {
      "document": {
        "id": "vec3",
        "text": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."
      },
      "index": 2,
      "score": 0.48357219
    },
    {
      "document": {
        "id": "vec1",
        "text": "Apple is a popular fruit known for its sweetness and crisp texture."
      },
      "index": 0,
      "score": 0.048405956
    },
    {
      "document": {
        "id": "vec4",
        "text": "An apple a day keeps the doctor away, as the saying goes."
      },
      "index": 3,
      "score": 0.007846239
    },
    {
      "document": {
        "id": "vec2",
        "text": "Many people enjoy eating apples as a healthy snack."
      },
      "index": 1,
      "score": 0.0006563728
    }
  ],
  "model": "bge-reranker-v2-m3",
  "usage": {
    "rerank_units": 1
  }
}
```

```csharp C# theme={null}
{
  "model": "bge-reranker-v2-m3",
  "data": [
    {
      "index": 2,
      "score": 0.48357219,
      "document": {
        "id": "vec3",
        "my_field": "Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."
      }
    },
    {
      "index": 0,
      "score": 0.048405956,
      "document": {
        "id": "vec1",
        "my_field": "Apple is a popular fruit known for its sweetness and crisp texture."
      }
    },
    {
      "index": 3,
      "score": 0.007846239,
      "document": {
        "id": "vec4",
        "my_field": "An apple a day keeps the doctor away, as the saying goes."
      }
    },
    {
      "index": 1,
      "score": 0.0006563728,
      "document": {
        "id": "vec2",
        "my_field": "Many people enjoy eating apples as a healthy snack."
      }
    }
  ],
  "usage": {
    "rerank_units": 1
  }
}
```

```JSON curl theme={null}
{
  "data":[
    {
      "index":2,
      "document":{
        "id":"vec3",
        "text":"Apple Inc. has revolutionized the tech industry with its sleek designs and user-friendly interfaces."
      },
      "score":0.47654688
    },
    {
      "index":0,
      "document":{
        "id":"vec1",
        "text":"Apple is a popular fruit known for its sweetness and crisp texture."
      },
      "score":0.047963805
    },
    {
      "index":3,
      "document":{
        "id":"vec4",
        "text":"An apple a day keeps the doctor away, as the saying goes."
      },
      "score":0.007587992
    },
    {
      "index":1,
      "document":{
        "id":"vec2",
        "text":"Many people enjoy eating apples as a healthy snack."
      },
      "score":0.0006491712
    }
  ],
  "usage":{
    "rerank_units":1
  }
}
```


## OpenAPI

````yaml https://raw.githubusercontent.com/pinecone-io/pinecone-api/refs/heads/main/2025-04/inference_2025-04.oas.yaml post /rerank
openapi: 3.0.3
info:
  title: Pinecone Inference API
  description: >-
    Pinecone is a vector database that makes it easy to search and retrieve
    billions of high-dimensional vectors.
  contact:
    name: Pinecone Support
    url: https://support.pinecone.io
    email: support@pinecone.io
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0
  version: 2025-04
servers:
  - url: https://api.pinecone.io
    description: Production API endpoints
security:
  - ApiKeyAuth: []
tags:
  - name: Inference
    description: Model inference
externalDocs:
  description: More Pinecone.io API docs
  url: https://docs.pinecone.io/introduction
paths:
  /rerank:
    post:
      tags:
        - Inference
      summary: Rerank documents
      description: >-
        Rerank results according to their relevance to a query.


        For guidance and examples, see [Rerank
        results](https://docs.pinecone.io/guides/search/rerank-results).
      operationId: rerank
      requestBody:
        description: Rerank documents for the given query
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RerankRequest'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RerankResult'
        '400':
          description: Bad request. The request body included invalid request parameters.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              examples:
                index-metric-validation-error:
                  summary: Validation error
                  value:
                    error:
                      code: INVALID_ARGUMENT
                      message: >-
                        Bad request. The request body included invalid request
                        parameters.
                    status: 400
        '401':
          description: 'Unauthorized. Possible causes: Invalid API key.'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              examples:
                unauthorized:
                  summary: Unauthorized
                  value:
                    error:
                      code: UNAUTHENTICATED
                      message: Invalid API key.
                    status: 401
        '500':
          description: Internal server error.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              examples:
                internal-server-error:
                  summary: Internal server error
                  value:
                    error:
                      code: UNKNOWN
                      message: Internal server error
                    status: 500
components:
  schemas:
    RerankRequest:
      type: object
      properties:
        model:
          example: bge-reranker-v2-m3
          description: >-
            The
            [model](https://docs.pinecone.io/guides/search/rerank-results#reranking-models)
            to use for reranking.
          type: string
        query:
          example: What is the capital of France?
          description: The query to rerank documents against.
          type: string
        top_n:
          example: 5
          description: >-
            The number of results to return sorted by relevance. Defaults to the
            number of inputs.
          type: integer
        return_documents:
          example: true
          description: Whether to return the documents in the response.
          default: true
          type: boolean
        rank_fields:
          description: >
            The field(s) to consider for reranking. If not provided, the default
            is `["text"]`.


            The number of fields supported is
            [model-specific](https://docs.pinecone.io/guides/search/rerank-results#reranking-models).
          default:
            - text
          type: array
          items:
            type: string
        documents:
          description: The documents to rerank.
          type: array
          items:
            $ref: '#/components/schemas/Document'
        parameters:
          example:
            truncate: END
          description: >-
            Additional model-specific parameters. Refer to the [model
            guide](https://docs.pinecone.io/guides/search/rerank-results#reranking-models)
            for available model parameters.
          type: object
          additionalProperties: true
      required:
        - model
        - documents
        - query
    RerankResult:
      description: The result of a reranking request.
      type: object
      properties:
        model:
          example: bge-reranker-v2-m3
          description: The model used to rerank documents.
          type: string
        data:
          description: The reranked documents.
          type: array
          items:
            $ref: '#/components/schemas/RankedDocument'
        usage:
          description: Usage statistics for the model inference.
          type: object
          properties:
            rerank_units:
              example: 1
              description: The number of rerank units consumed by this operation.
              type: integer
              format: int32
              minimum: 0
      required:
        - model
        - data
        - usage
    ErrorResponse:
      example:
        error:
          code: QUOTA_EXCEEDED
          message: >-
            The index exceeds the project quota of 5 pods by 2 pods. Upgrade
            your account or change the project settings to increase the quota.
        status: 429
      description: The response shape used for all error responses.
      type: object
      properties:
        status:
          example: 500
          description: The HTTP status code of the error.
          type: integer
        error:
          example:
            code: INVALID_ARGUMENT
            message: >-
              Index name must contain only lowercase alphanumeric characters or
              hyphens, and must not begin or end with a hyphen.
          description: Detailed information about the error that occurred.
          type: object
          properties:
            code:
              type: string
              enum:
                - OK
                - UNKNOWN
                - INVALID_ARGUMENT
                - DEADLINE_EXCEEDED
                - QUOTA_EXCEEDED
                - NOT_FOUND
                - ALREADY_EXISTS
                - PERMISSION_DENIED
                - UNAUTHENTICATED
                - RESOURCE_EXHAUSTED
                - FAILED_PRECONDITION
                - ABORTED
                - OUT_OF_RANGE
                - UNIMPLEMENTED
                - INTERNAL
                - UNAVAILABLE
                - DATA_LOSS
                - FORBIDDEN
            message:
              example: >-
                Index name must contain only lowercase alphanumeric characters
                or hyphens, and must not begin or end with a hyphen.
              type: string
            details:
              description: >-
                Additional information about the error. This field is not
                guaranteed to be present.
              type: object
          required:
            - code
            - message
      required:
        - status
        - error
    Document:
      example:
        id: '1'
        text: Paris is the capital of France.
        title: France
        url: https://example.com
      description: Document for reranking
      type: object
      additionalProperties: true
    RankedDocument:
      description: A ranked document with a relevance score and an index position.
      type: object
      properties:
        index:
          description: The index position of the document from the original request.
          type: integer
        score:
          example: 0.5
          description: >-
            The relevance of the document to the query, normalized between 0 and
            1, with scores closer to 1 indicating higher relevance.
          type: number
        document:
          $ref: '#/components/schemas/Document'
      required:
        - index
        - score
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: Api-Key
      description: >-
        An API Key is required to call Pinecone APIs. Get yours from the
        [console](https://app.pinecone.io/).

````