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

# Indexar e buscar texto

> Use o Text Store para busca vetorial pré-configurada ou Tables para controle de baixo nível sobre esquema, índices e operações de busca.

A API de Busca fornece duas maneiras de armazenar e recuperar textos:

* **Text Store** — armazenamento vetorial pré-configurado com busca híbrida, desduplicação e agrupamento. Não é necessário configurar esquema ou índice.
* **Tables** — acesso de baixo nível ao banco de dados vetorial com controle total sobre esquema, índices, filtros e operações de busca.

Comece com o Text Store para a maioria dos casos de uso.
Use Tables quando precisar de esquemas personalizados, gerenciamento explícito de índices ou expressões de filtro avançadas.

Se você precisa de um exemplo externo que mostre o GraphRAG superando a recuperação plana em um benchmark definido, veja [Avaliação do GraphRAG](/pt/docs/graphrag).

## Criar um text store

Forneça um nome e a dimensão do embedding para seus vetores.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search text-store create \
    -H 'X-On-Behalf-Of: <end-user-id>' \
    --body '{
      "store_name": "product_catalog",
      "dimension": 3
    }'
  ```

  ```ts MKA1 SDK theme={null}
  import { SDK } from '@meetkai/mka1';

  const mka1 = new SDK({ bearerAuth: '<mka1-api-key>' });

  const response = await mka1.search.textStore.createStore(
    {
      storeName: 'product_catalog',
      dimension: 3,
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.TextStore.CreateTextStoreAsync(
      xApiKeyId: "<id>",
      xUserId: "<id>",
      xExchangeJwtExternalUserId: "<id>",
      body: new CreateTextStoreRequest
      {
          StoreName = "product_catalog",
          Dimension = 3,
      }
  );
  ```

  ```python Python SDK theme={null}
  from mka1 import SDK

  sdk = SDK(bearer_auth="Bearer YOUR_API_KEY")

  response = sdk.search.text_store.create_text_store(
      store_name="product_catalog",
      dimension=3,
      x_api_key_id="<api-key-id>",
      x_user_id="<user-id>",
      x_exchange_jwt_external_user_id="<external-user-id>",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/text-store/stores \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'x-api-key-id: <id>' \
    --header 'x-user-id: <id>' \
    --header 'x-exchange-jwt-external-user-id: <id>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "store_name": "product_catalog",
      "dimension": 3
    }'
  ```
</CodeGroup>

## Adicionar textos a um text store

Adicione textos com seus vetores de embedding pré-computados.
Textos duplicados são automaticamente ignorados.
O campo `group` marca as entradas para que você possa deletá-las ou recuperá-las como um conjunto posteriormente.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search text-store add-texts \
    --store-name product_catalog \
    --body '{
      "texts": [
        "Noise-cancelling over-ear headphones with 30-hour battery.",
        "Compact wireless earbuds with active noise cancellation.",
        "Studio monitor headphones with flat frequency response."
      ],
      "vectors": [
        [0.16, -0.08, 0.29],
        [0.14, -0.06, 0.31],
        [0.09, -0.12, 0.22]
      ],
      "group": "headphones"
    }'
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.textStore.addTexts(
    {
      storeName: 'product_catalog',
      addTextsRequest: {
        texts: [
          'Noise-cancelling over-ear headphones with 30-hour battery.',
          'Compact wireless earbuds with active noise cancellation.',
          'Studio monitor headphones with flat frequency response.',
        ],
        vectors: [
          [0.16, -0.08, 0.29],
          [0.14, -0.06, 0.31],
          [0.09, -0.12, 0.22],
        ],
        group: 'headphones',
      },
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.TextStore.AddTextsAsync(
      new MeetKai.MKA1.Types.Requests.AddTextsRequest
      {
          StoreName = "product_catalog",
          XApiKeyId = "<id>",
          XUserId = "<id>",
          XExchangeJwtExternalUserId = "<id>",
          Body = new AddTextsRequest
          {
              Texts = new List<string>
              {
                  "Noise-cancelling over-ear headphones with 30-hour battery.",
                  "Compact wireless earbuds with active noise cancellation.",
                  "Studio monitor headphones with flat frequency response.",
              },
              Vectors = new List<List<double>>
              {
                  new List<double> { 0.16, -0.08, 0.29 },
                  new List<double> { 0.14, -0.06, 0.31 },
                  new List<double> { 0.09, -0.12, 0.22 },
              },
              Group = "headphones",
          },
      }
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.text_store.add_texts(
      store_name="product_catalog",
      texts=[
          "Noise-cancelling over-ear headphones with 30-hour battery.",
          "Compact wireless earbuds with active noise cancellation.",
          "Studio monitor headphones with flat frequency response.",
      ],
      vectors=[
          [0.16, -0.08, 0.29],
          [0.14, -0.06, 0.31],
          [0.09, -0.12, 0.22],
      ],
      group="headphones",
      x_api_key_id="<api-key-id>",
      x_user_id="<user-id>",
      x_exchange_jwt_external_user_id="<external-user-id>",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/text-store/stores/product_catalog/texts \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'x-api-key-id: <id>' \
    --header 'x-user-id: <id>' \
    --header 'x-exchange-jwt-external-user-id: <id>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "texts": [
        "Noise-cancelling over-ear headphones with 30-hour battery.",
        "Compact wireless earbuds with active noise cancellation.",
        "Studio monitor headphones with flat frequency response."
      ],
      "vectors": [
        [0.16, -0.08, 0.29],
        [0.14, -0.06, 0.31],
        [0.09, -0.12, 0.22]
      ],
      "group": "headphones"
    }'
  ```
</CodeGroup>

## Buscar em um text store

Passe uma consulta de texto e seu vetor de embedding.
O serviço executa uma busca híbrida combinando similaridade de texto completo e vetorial.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search text-store search-texts \
    --store-name product_catalog \
    --body '{
      "query": "noise-cancelling headphones",
      "vector": [0.16, -0.08, 0.29],
      "limit": 5
    }'
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.textStore.search(
    {
      storeName: 'product_catalog',
      searchTextsRequest: {
        query: 'noise-cancelling headphones',
        vector: [0.16, -0.08, 0.29],
        limit: 5,
      },
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.TextStore.SearchTextsAsync(
      new MeetKai.MKA1.Types.Requests.SearchTextsRequest
      {
          StoreName = "product_catalog",
          XApiKeyId = "<id>",
          XUserId = "<id>",
          XExchangeJwtExternalUserId = "<id>",
          Body = new SearchTextRequest
          {
              Query = "noise-cancelling headphones",
              Vector = new List<double> { 0.16, -0.08, 0.29 },
              Limit = 5,
          },
      }
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.text_store.search_texts(
      store_name="product_catalog",
      query="noise-cancelling headphones",
      vector=[0.16, -0.08, 0.29],
      x_api_key_id="<api-key-id>",
      x_user_id="<user-id>",
      x_exchange_jwt_external_user_id="<external-user-id>",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/text-store/stores/product_catalog/search \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'x-api-key-id: <id>' \
    --header 'x-user-id: <id>' \
    --header 'x-exchange-jwt-external-user-id: <id>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "query": "noise-cancelling headphones",
      "vector": [0.16, -0.08, 0.29],
      "limit": 5
    }'
  ```
</CodeGroup>

## Deletar texto de um text store

Remova entradas específicas pelos seus valores de texto exatos.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search text-store delete-texts \
    --store-name product_catalog \
    --body '{
      "texts": [
        "Studio monitor headphones with flat frequency response."
      ]
    }'
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.textStore.deleteTexts(
    {
      storeName: 'product_catalog',
      deleteTextsRequest: {
        texts: [
          'Studio monitor headphones with flat frequency response.',
        ],
      },
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.TextStore.DeleteTextsAsync(
      new MeetKai.MKA1.Types.Requests.DeleteTextsRequest
      {
          StoreName = "product_catalog",
          XApiKeyId = "<id>",
          XUserId = "<id>",
          XExchangeJwtExternalUserId = "<id>",
          Body = new DeleteTextsRequest
          {
              Texts = new List<string>
              {
                  "Studio monitor headphones with flat frequency response.",
              },
          },
      }
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.text_store.delete_texts(
      store_name="product_catalog",
      texts=[
          "Studio monitor headphones with flat frequency response.",
      ],
      x_api_key_id="<api-key-id>",
      x_user_id="<user-id>",
      x_exchange_jwt_external_user_id="<external-user-id>",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/text-store/stores/product_catalog/texts \
    --request DELETE \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'x-api-key-id: <id>' \
    --header 'x-user-id: <id>' \
    --header 'x-exchange-jwt-external-user-id: <id>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "texts": [
        "Studio monitor headphones with flat frequency response."
      ]
    }'
  ```
</CodeGroup>

## Deletar textos por grupo de um text store

Remova todas as entradas que pertencem a um ou mais grupos.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search text-store delete-texts \
    --store-name product_catalog \
    --body '{
      "groups": ["headphones"]
    }'
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.textStore.deleteTexts(
    {
      storeName: 'product_catalog',
      deleteTextsRequest: {
        groups: ['headphones'],
      },
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.TextStore.DeleteTextsAsync(
      new MeetKai.MKA1.Types.Requests.DeleteTextsRequest
      {
          StoreName = "product_catalog",
          XApiKeyId = "<id>",
          XUserId = "<id>",
          XExchangeJwtExternalUserId = "<id>",
          Body = new DeleteTextsRequest
          {
              Groups = new List<string> { "headphones" },
          },
      }
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.text_store.delete_texts(
      store_name="product_catalog",
      texts=["headphones"],
      x_api_key_id="<api-key-id>",
      x_user_id="<user-id>",
      x_exchange_jwt_external_user_id="<external-user-id>",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/text-store/stores/product_catalog/texts \
    --request DELETE \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'x-api-key-id: <id>' \
    --header 'x-user-id: <id>' \
    --header 'x-exchange-jwt-external-user-id: <id>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "groups": ["headphones"]
    }'
  ```
</CodeGroup>

## Deletar um text store

Remova o store e todos os seus dados.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search text-store delete --store-name product_catalog
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.textStore.deleteStore(
    { storeName: 'product_catalog' },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.TextStore.DeleteTextStoreAsync(
      storeName: "product_catalog",
      xApiKeyId: "<id>",
      xUserId: "<id>",
      xExchangeJwtExternalUserId: "<id>"
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.text_store.delete_text_store(
      store_name="product_catalog",
      x_api_key_id="<api-key-id>",
      x_user_id="<user-id>",
      x_exchange_jwt_external_user_id="<external-user-id>",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/text-store/stores/product_catalog \
    --request DELETE \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'x-api-key-id: <id>' \
    --header 'x-user-id: <id>' \
    --header 'x-exchange-jwt-external-user-id: <id>' \
    --header 'X-On-Behalf-Of: <end-user-id>'
  ```
</CodeGroup>

## Uso Avançado: Tables

Tables fornecem acesso direto ao banco de dados vetorial subjacente.
Você define o esquema, escolhe quais campos indexar, insere linhas estruturadas e compõe operações de busca manualmente.

### Campos do esquema

Cada campo em um esquema de tabela possui um `name`, `type` e propriedades opcionais.

| Tipo       | Descrição                           | Suporte a índice                                   |
| ---------- | ----------------------------------- | -------------------------------------------------- |
| `string`   | Dados de texto                      | `FTS` (busca de texto completo)                    |
| `int`      | Inteiro 32 bits                     | `BTREE`, `BITMAP`, `LABEL_LIST`                    |
| `float`    | Ponto flutuante 64 bits             | `BTREE`, `BITMAP`, `LABEL_LIST`                    |
| `datetime` | Timestamp com fuso horário opcional | `BTREE`                                            |
| `vector`   | Embedding de dimensão fixa          | `IVF_FLAT`, `IVF_PQ`, `IVF_HNSW_PQ`, `IVF_HNSW_SQ` |
| `list`     | Lista de strings, ints ou floats    | —                                                  |

Defina `nullable` como `false` para campos obrigatórios.
Adicione `"index": "FTS"` em um campo string para habilitar busca de texto completo na criação.
Campos vetoriais exigem a propriedade `dimensions` que deve corresponder ao tamanho do seu embedding.

### Criar uma tabela de busca

Defina uma tabela com um esquema que descreva seus registros.
O exemplo abaixo cria uma base de conhecimento de suporte com um campo de texto indexado para busca de texto completo e um campo vetorial para busca semântica.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search tables create \
    --body '{
      "name": "support_kb",
      "schema": {
        "fields": [
          { "name": "id", "type": "string", "nullable": false },
          { "name": "content", "type": "string", "nullable": false, "index": "FTS" },
          { "name": "category", "type": "string", "nullable": false },
          { "name": "rating", "type": "float", "nullable": true },
          { "name": "embedding", "type": "vector", "nullable": false, "dimensions": 3 }
        ]
      }
    }'
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.tables.create(
    {
      name: 'support_kb',
      schema: {
        fields: [
          { name: 'id', type: 'string', nullable: false },
          { name: 'content', type: 'string', nullable: false, index: 'FTS' },
          { name: 'category', type: 'string', nullable: false },
          { name: 'rating', type: 'float', nullable: true },
          { name: 'embedding', type: 'vector', nullable: false, dimensions: 3 },
        ],
      },
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.Tables.CreateTableAsync(
      new CreateTableRequest
      {
          Name = "support_kb",
          Schema = new TableSchemaInput
          {
              Fields = new List<TableSchemaInputField>
              {
                  TableSchemaInputField.CreateString(new StringField
                  {
                      Name = "id", Nullable = false,
                  }),
                  TableSchemaInputField.CreateString(new StringField
                  {
                      Name = "content", Nullable = false,
                      Index = StringIndexType.Fts,
                  }),
                  TableSchemaInputField.CreateString(new StringField
                  {
                      Name = "category", Nullable = false,
                  }),
                  TableSchemaInputField.CreateFloat(new FloatField
                  {
                      Name = "rating", Nullable = true,
                  }),
                  TableSchemaInputField.CreateVector(new VectorField
                  {
                      Name = "embedding", Nullable = false,
                      Dimensions = 3,
                  }),
              },
          },
      }
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.tables.create_table(
      name="support_kb",
      schema={
          "fields": [
              {"name": "id", "type": "string", "nullable": False},
              {"name": "content", "type": "string", "nullable": False, "index": "FTS"},
              {"name": "category", "type": "string", "nullable": False},
              {"name": "rating", "type": "float", "nullable": True},
              {"name": "embedding", "type": "vector", "nullable": False, "dimensions": 3},
          ],
      },
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/tables \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "name": "support_kb",
      "schema": {
        "fields": [
          {
            "name": "id",
            "type": "string",
            "nullable": false
          },
          {
            "name": "content",
            "type": "string",
            "nullable": false,
            "index": "FTS"
          },
          {
            "name": "category",
            "type": "string",
            "nullable": false
          },
          {
            "name": "rating",
            "type": "float",
            "nullable": true
          },
          {
            "name": "embedding",
            "type": "vector",
            "nullable": false,
            "dimensions": 3
          }
        ]
      }
    }'
  ```
</CodeGroup>

### Inserir linhas

Insira registros que correspondam ao esquema da tabela.
Você pode enviar várias linhas em uma única requisição.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search tables insert-data \
    --table-name support_kb \
    --body '{
      "data": [
        {
          "id": "doc_001",
          "content": "Reset your password from the account settings page.",
          "category": "account",
          "rating": 4.7,
          "embedding": [0.13, -0.09, 0.41]
        },
        {
          "id": "doc_002",
          "content": "Use two-factor authentication for added account security.",
          "category": "security",
          "rating": 4.9,
          "embedding": [0.07, -0.02, 0.36]
        }
      ]
    }'
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.tables.insertData(
    {
      tableName: 'support_kb',
      insertDataRequest: {
        data: [
          {
            id: 'doc_001',
            content: 'Reset your password from the account settings page.',
            category: 'account',
            rating: 4.7,
            embedding: [0.13, -0.09, 0.41],
          },
          {
            id: 'doc_002',
            content: 'Use two-factor authentication for added account security.',
            category: 'security',
            rating: 4.9,
            embedding: [0.07, -0.02, 0.36],
          },
        ],
      },
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.Tables.InsertDataAsync(
      tableName: "support_kb",
      body: new InsertDataRequest
      {
          Data = new List<Dictionary<string, object>>
          {
              new Dictionary<string, object>
              {
                  { "id", "doc_001" },
                  { "content", "Reset your password from the account settings page." },
                  { "category", "account" },
                  { "rating", 4.7 },
                  { "embedding", new List<double> { 0.13, -0.09, 0.41 } },
              },
              new Dictionary<string, object>
              {
                  { "id", "doc_002" },
                  { "content", "Use two-factor authentication for added account security." },
                  { "category", "security" },
                  { "rating", 4.9 },
                  { "embedding", new List<double> { 0.07, -0.02, 0.36 } },
              },
          },
      }
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.tables.insert_data(
      table_name="support_kb",
      data=[
          {
              "id": "doc_001",
              "content": "Reset your password from the account settings page.",
              "category": "account",
              "rating": 4.7,
              "embedding": [0.13, -0.09, 0.41],
          },
          {
              "id": "doc_002",
              "content": "Use two-factor authentication for added account security.",
              "category": "security",
              "rating": 4.9,
              "embedding": [0.07, -0.02, 0.36],
          },
      ],
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/tables/support_kb/data \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "data": [
        {
          "id": "doc_001",
          "content": "Reset your password from the account settings page.",
          "category": "account",
          "rating": 4.7,
          "embedding": [0.13, -0.09, 0.41]
        },
        {
          "id": "doc_002",
          "content": "Use two-factor authentication for added account security.",
          "category": "security",
          "rating": 4.9,
          "embedding": [0.07, -0.02, 0.36]
        }
      ]
    }'
  ```
</CodeGroup>

### Operações de busca

A busca em tabelas permite compor múltiplas operações em uma única requisição.
As operações são executadas em ordem — comece com uma busca primária, depois refine com filtros, limites ou offsets.

**Operações primárias** inicializam o conjunto de resultados:

| Operação        | Descrição                                                                                                            |
| --------------- | -------------------------------------------------------------------------------------------------------------------- |
| `vector_search` | Encontra linhas mais próximas de um vetor de consulta. Suporta tipos de distância `cosine`, `l2`, `dot` e `hamming`. |
| `fts`           | Busca por palavra-chave em texto completo em um ou mais campos string.                                               |

**Operações secundárias** refinam os resultados:

| Operação | Descrição                                                                                               |
| -------- | ------------------------------------------------------------------------------------------------------- |
| `filter` | Aplica uma expressão similar ao SQL. Defina `prefilter` como `true` para filtrar antes do ranqueamento. |
| `limit`  | Limita o número de linhas retornadas.                                                                   |
| `offset` | Pula as primeiras N linhas para paginação.                                                              |

Use `returnColumns` para controlar quais campos retornam na resposta.

### Buscar na tabela

O exemplo abaixo combina uma busca vetorial com um pré-filtro no campo `category`.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search tables search-data \
    --table-name support_kb \
    --body '{
      "operations": [
        {
          "type": "vector_search",
          "field": "embedding",
          "vector": [0.11, -0.06, 0.37],
          "distanceType": "cosine",
          "limit": 5
        },
        {
          "type": "filter",
          "expression": "category = '\''security'\''",
          "prefilter": true
        }
      ],
      "returnColumns": ["id", "content", "category", "rating"]
    }'
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.tables.search(
    {
      tableName: 'support_kb',
      searchRequest: {
        operations: [
          {
            type: 'vector_search',
            field: 'embedding',
            vector: [0.11, -0.06, 0.37],
            distanceType: 'cosine',
            limit: 5,
          },
          {
            type: 'filter',
            expression: "category = 'security'",
            prefilter: true,
          },
        ],
        returnColumns: ['id', 'content', 'category', 'rating'],
      },
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.Tables.SearchDataAsync(
      tableName: "support_kb",
      body: new SearchRequest
      {
          Operations = new List<Operation>
          {
              Operation.CreateVectorSearch(new VectorSearchOperation
              {
                  Field = "embedding",
                  Vector = Vector.CreateArrayOfNumber(
                      new List<double> { 0.11, -0.06, 0.37 }
                  ),
                  DistanceType = DistanceType.Cosine,
                  Limit = 5,
              }),
              Operation.CreateFilter(new FilterOperation
              {
                  Expression = "category = 'security'",
                  Prefilter = true,
              }),
          },
          ReturnColumns = new List<string> { "id", "content", "category", "rating" },
      }
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.tables.search_data(
      table_name="support_kb",
      operations=[
          {
              "type": "vector_search",
              "field": "embedding",
              "vector": [0.11, -0.06, 0.37],
              "distanceType": "cosine",
              "limit": 5,
          },
          {
              "type": "filter",
              "expression": "category = 'security'",
              "prefilter": True,
          },
      ],
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/tables/support_kb/search \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "operations": [
        {
          "type": "vector_search",
          "field": "embedding",
          "vector": [0.11, -0.06, 0.37],
          "distanceType": "cosine",
          "limit": 5
        },
        {
          "type": "filter",
          "expression": "category = '\''security'\''",
          "prefilter": true
        }
      ],
      "returnColumns": [
        "id",
        "content",
        "category",
        "rating"
      ]
    }'
  ```
</CodeGroup>

### Deletar linhas

Remova linhas de uma tabela usando uma expressão de filtro.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search tables delete-data \
    --table-name support_kb \
    --body '{
      "filter": "id IN ('\''doc_001'\'', '\''doc_002'\'')"
    }'
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.tables.deleteData(
    {
      tableName: 'support_kb',
      deleteDataRequest: {
        filter: "id IN ('doc_001', 'doc_002')",
      },
    },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.Tables.DeleteDataAsync(
      tableName: "support_kb",
      body: new DeleteDataRequest
      {
          Filter = "id IN ('doc_001', 'doc_002')",
      }
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.tables.delete_data(
      table_name="support_kb",
      filter_="id IN ('doc_001', 'doc_002')",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/tables/support_kb/data \
    --request DELETE \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "filter": "id IN ('\''doc_001'\'', '\''doc_002'\'')"
    }'
  ```
</CodeGroup>

### Deletar uma tabela

Remova a tabela e todos os seus dados.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 search tables delete --table-name support_kb
  ```

  ```ts MKA1 SDK theme={null}
  const response = await mka1.search.tables.delete(
    { tableName: 'support_kb' },
    { headers: { 'X-On-Behalf-Of': '<end-user-id>' } }
  );
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;

  var sdk = new SDK(
      bearerAuth: "Bearer <mka1-api-key>",
      serverUrl: "https://apigw.mka1.com"
  );

  var response = await sdk.Search.Tables.DeleteTableAsync(
      tableName: "support_kb"
  );
  ```

  ```python Python SDK theme={null}
  response = sdk.search.tables.delete_table(
      table_name="support_kb",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/search/tables/support_kb \
    --request DELETE \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>'
  ```
</CodeGroup>
