Skip to content

Filter Documents

Filter documents by applying filter criteria, without performing text search.

This is useful for cases which only require querying document attributes (rather than searching text in the documents). For example:

  • Finding stores within 5 miles of the user
  • Documents updated within the last 24 hours

Endpoint

POST /v20241104/filter

API Request

  • Required Parameters

    filter object required

    JSON object specifying the filter criteria.


    Optional Parameters


    facet array of strings

    Array specifying the facet criteria.


    facet_advanced array of objects

    Array of JSON objects specifying advanced facet criteria.


    language string (enum)

    Language code (of a supported language) that indicates the language of the documents to filter.


    limit integer

    Limit on the maximum number of results to return per request. Default is 10.

    Additional results can be fetched if more are available.

    Min: 1   Max: 100


    page integer

    A cursor used for pagination when there are multiple pages of results. Default is 1.

    Info
    • Don't include this parameter in the initial API request.
    • Set this to the next_page value from the previous API response to fetch the subsequent page of results.

    Min: 1


    sort array of objects

    An array of JSON objects specifying sort criteria for the search results.


    tenant_id array of strings

    Array specifying one or more Tenant IDs.

    Info
    • Only documents with a tenant_id matching one of the values in the array will be considered.

    • Example (single tenant ID):

      "tenant_id": ["tenant123"],
      

    • Example (multiple tenant IDs):

      "tenant_id": ["tenant123", "tenant124"],
      

    • For each tenant ID string:

      MinLength: 1   MaxLength: 250

    MinLength: 1   MaxLength: 10

  • POST /v20241104/filter


    curl -X POST "https://api.gainly.ai/v20241104/filter" \
      -H "Content-Type: application/json" \
      -H "X-API-Key: YOUR_API_KEY_HERE" \  # (1)!
      -d '{
        "filter": {
            "must": [
                {
                    "range": {
                        "created_at": {
                            "gte": "2024-09-10"
                        }
                    }
                }
            ]
        }
      }'
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    # Prompt for AI coding assistants/IDEs (e.g., ChatGPT, Claude, GitHub Copilot, Cursor, Windsurf)
    
    Using the Gainly API:
    1. Write code to call the filter_documents operation (see OpenAPI spec: https://api.gainly.ai/v20241104/openapi.json)
    2. Implement authentication using the header "X-API-Key" as described in the docs: https://docs.gainly.ai/latest/api-reference/authentication/
    3. Implement rate limit handling as described in the docs: https://docs.gainly.ai/latest/api-reference/rate-limits/
    4. Implement error handling
    5. Handle the response according to the FilterResults schema in the OpenAPI spec
    6. Implement pagination to handle multiple pages of results as described in the docs: https://docs.gainly.ai/latest/docs/pagination/
    
    using System.Net.Http;
    using System.Text.Json;
    using System.Text;
    
    var client = new HttpClient();
    
    var url = "https://api.gainly.ai/v20241104/filter";
    
    var payload = new {
        filter = new {
            must = new[] {
                new {
                    range = new {
                        created_at = new {
                            gte = "2024-09-10"
                        }
                    }
                }
            }
        }
    };
    
    var content = new StringContent(
        JsonSerializer.Serialize(payload),
        Encoding.UTF8,
        "application/json"
    );
    
    client.DefaultRequestHeaders.Add("X-API-Key", "YOUR_API_KEY_HERE"); // (1)!
    
    var response = await client.PostAsync(url, content);
    var result = await response.Content.ReadAsStringAsync();
    Console.WriteLine(result);
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    package main
    
    import (
        "bytes"
        "encoding/json"
        "fmt"
        "net/http"
    )
    
    func main() {
        url := "https://api.gainly.ai/v20241104/filter"
    
        payload := map[string]interface{}{
            "filter": map[string]interface{}{
                "must": []map[string]interface{}{
                    {
                        "range": map[string]interface{}{
                            "created_at": map[string]interface{}{
                                "gte": "2024-09-10",
                            },
                        },
                    },
                },
            },
        }
    
        jsonData, _ := json.Marshal(payload)
    
        req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("X-API-Key", "YOUR_API_KEY_HERE") // (1)!
    
        resp, _ := http.DefaultClient.Do(req)
        defer resp.Body.Close()
    
        var result map[string]interface{}
        json.NewDecoder(resp.Body).Decode(&result)
        fmt.Println(result)
    }
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.net.URI;
    
    var client = HttpClient.newHttpClient();
    
    var url = "https://api.gainly.ai/v20241104/filter";
    
    var payload = """
        {
            "filter": {
                "must": [
                    {
                        "range": {
                            "created_at": {
                                "gte": "2024-09-10"
                            }
                        }
                    }
                ]
            }
        }
        """;
    
    var request = HttpRequest.newBuilder()
        .uri(URI.create(url))
        .header("Content-Type", "application/json")
        .header("X-API-Key", "YOUR_API_KEY_HERE") // (1)!
        .POST(HttpRequest.BodyPublishers.ofString(payload))
        .build();
    
    var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.body());
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    const axios = require('axios');  // or: import axios from 'axios';
    
    const url = 'https://api.gainly.ai/v20241104/filter';
    
    const payload = {
        filter: {
            must: [
                {
                    range: {
                        created_at: {
                            gte: "2024-09-10"
                        }
                    }
                }
            ]
        }
    };
    
    const headers = {
        'Content-Type': 'application/json',
        'X-API-Key': 'YOUR_API_KEY_HERE' // (1)!
    };
    
    axios.post(url, payload, { headers })
        .then(response => console.log(response.data))
        .catch(error => console.error('Error:', error.message));
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    <?php
    
    $client = new \GuzzleHttp\Client();
    
    $url = 'https://api.gainly.ai/v20241104/filter';
    
    $payload = [
        'filter' => [
            'must' => [
                [
                    'range' => [
                        'created_at' => [
                            'gte' => '2024-09-10'
                        ]
                    ]
                ]
            ]
        ]
    ];
    
    $response = $client->request('POST', $url, [
        'json' => $payload,
        'headers' => [
            'Content-Type' => 'application/json',
            'X-API-Key' => 'YOUR_API_KEY_HERE' # (1)!
        ],
    ]);
    
    echo $response->getBody();
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    import requests
    
    url = "https://api.gainly.ai/v20241104/filter"
    
    payload = {
        "filter": {
            "must": [
                {
                    "range": {
                        "created_at": {
                            "gte": "2024-09-10"
                        }
                    }
                }
            ]
        }
    }
    
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": "YOUR_API_KEY_HERE" # (1)!
    }
    
    response = requests.post(url, json=payload, headers=headers)
    data = response.json()
    print(data)
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.
    require 'json'
    require 'uri'
    require 'net/http'
    require 'openssl'
    
    url = URI('https://api.gainly.ai/v20241104/filter')
    
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    
    request = Net::HTTP::Post.new(url)
    request['Content-Type'] = 'application/json'
    request['X-API-Key'] = 'YOUR_API_KEY_HERE' # (1)!
    request.body = {
        filter: {
            must: [
                {
                    range: {
                        created_at: {
                            gte: "2024-09-10"
                        }
                    }
                }
            ]
        }
    }.to_json
    
    response = http.request(request)
    puts response.read_body
    
    1. Replace YOUR_API_KEY_HERE with the value of your API key.

API Response

{
    "object": "filter_result",
    "url": "/v20241104/filter",
    "data": [
        {
            "id": "4nD1gZIB7caKVIeL2MgL",
            "title": "awesome document with my search terms",
            "source_uri": "/doc/7-awesome-document-with-my-search-terms",
            "metadata": null,
            "tenant_id": "tenant123",
            "language": "en",
            "sort_value": null,
            "created_at": "2024-09-12T21:58:53Z",
            "updated_at": "2024-09-12T12:28:12Z"
        },
        {
            "id": "B3AegpIB7caKVIeL78nJ",
            "title": "another great document",
            "source_uri": "/doc/12-another-great-document",
            "metadata": null,
            "tenant_id": "tenant123",
            "language": "en",
            "sort_value": null,
            "created_at": "2024-09-12T15:58:53Z",
            "updated_at": "2024-09-13T05:23:05Z"
        }
    ],
    "tenant_id": null,
    "filter": {
        "must": [
            {
                "range": {
                    "created_at": {
                        "gte": "2024-09-10"
                    }
                }
            }
        ],
        "must_not": [],
        "should": [],
        "minimum_should_match": null
    },
    "sort": [
        {
            "_score": {
                "order": "desc"
            }
        }
    ],
    "facet": null,
    "facet_advanced": null,
    "facet_result": null,
    "language": null,
    "has_more": false,
    "next_page": null,
    "total_number_of_results": 2,
    "page": 1,
    "limit": 10,
    "token_usage": {
        "semantic_tokens": 0,
        "llm_tokens": {
            "llm_output_tokens": 0,
            "llm_input_tokens": 0,
            "model": null
        }
    },
    "livemode": false
}

Facet Result

Please see basic faceting and advanced faceting for details on the facet_result property.

Pagination

Please see pagination for details on navigating multiple pages of results.