Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›Поиск данных ›Семантический поиск

Учебник: семантический поиск с API вывода

В этом учебнике показано, как использовать рабочие процессы API вывода с различными сервисами для выполнения семантического поиска в ваших данных.

Для самого простого способа выполнения семантического поиска в Elastic Stack обратитесь к semantic_text пошаговому руководству.

В следующих примерах используются:

  • embed-english-v3.0 модель для Cohere
  • all-mpnet-base-v2 модель от HuggingFace
  • text-embedding-ada-002 модель встраивания второго поколения для OpenAI
  • модели, доступные через Azure AI Studio или Azure OpenAI
  • text-embedding-004 модель для Google Vertex AI
  • mistral-embed модель для Mistral
  • amazon.titan-embed-text-v1 модель для Amazon Bedrock
  • ops-text-embedding-zh-001 модель для AlibabaCloud AI

Вы можете использовать любые модели Cohere и OpenAI, они все поддерживаются API вывода. Для получения списка рекомендуемых моделей, доступных в HuggingFace, обратитесь к списку поддерживаемых моделей.

Нажмите на имя сервиса, который вы хотите использовать, на одном из виджетов ниже, чтобы просмотреть соответствующие инструкции.

Требования

Для использования API вывода с сервисом Cohere требуется учетная запись Cohere.

ELSER — это модель, обученная Elastic. Если у вас есть развертывание Elasticsearch, дополнительных требований для использования API вывода с сервисом elasticsearch нет.

Для использования API вывода с сервисом HuggingFace требуется учетная запись HuggingFace.

Для использования API вывода с сервисом OpenAI требуется учетная запись OpenAI.

  • Подписка Azure
  • Предоставленный доступ к Azure OpenAI в необходимой подписке Azure. Вы можете подать заявку на доступ к Azure OpenAI, заполнив форму по адресу https://aka.ms/oai/access.
  • Модель встраивания, развернутая в Azure OpenAI Studio.

Создайте конечную точку вывода

Создайте конечную точку вывода, используя создание API вывода:

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="cohere_embeddings",
    inference_config={
        "service": "cohere",
        "service_settings": {
            "api_key": "<api_key>",
            "model_id": "embed-english-v3.0",
            "embedding_type": "byte"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "cohere_embeddings",
  inference_config: {
    service: "cohere",
    service_settings: {
      api_key: "<api_key>",
      model_id: "embed-english-v3.0",
      embedding_type: "byte",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/cohere_embeddings 
{
    "service": "cohere",
    "service_settings": {
        "api_key": "<api_key>", 
        "model_id": "embed-english-v3.0", 
        "embedding_type": "byte"
    }
}

Тип задачи — text_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки инференции, — cohere_embeddings.

Ключ API вашей учётной записи Cohere. Вы можете найти ключи API в своём панеле управления Cohere в разделе «Ключи API» здесь. Ключ API необходимо указать только один раз. API для получения конечной точки инференции не возвращает ключ API.

Название модели встраивания, которую нужно использовать. Список моделей встраивания Cohere можно найти здесь.

При использовании этой модели рекомендуется использовать меру сходства dense_vector в поле сопоставления dot_product. В случае с моделями Cohere векторы встраивания нормализуются до единичной длины, поэтому меры dot_product и cosine эквивалентны.

resp = client.inference.put(
    task_type="sparse_embedding",
    inference_id="elser_embeddings",
    inference_config={
        "service": "elasticsearch",
        "service_settings": {
            "num_allocations": 1,
            "num_threads": 1
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "sparse_embedding",
  inference_id: "elser_embeddings",
  inference_config: {
    service: "elasticsearch",
    service_settings: {
      num_allocations: 1,
      num_threads: 1,
    },
  },
});
console.log(response);
PUT _inference/sparse_embedding/elser_embeddings 
{
  "service": "elasticsearch",
  "service_settings": {
    "num_allocations": 1,
    "num_threads": 1
  }
}

Тип задачи — sparse_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки инференции, — elser_embeddings.

Вам не нужно загружать и развертывать модель ELSER заранее, API-запрос выше загрузит модель, если она ещё не загружена, и затем развернёт её.

При использовании консоли Kibana в ответе может появиться ошибка 502 (bad gateway). Эта ошибка, как правило, просто отражает таймаут, в то время как модель загружается в фоновом режиме. Вы можете отследить процесс загрузки в пользовательском интерфейсе машинного обучения. При использовании Python-клиента вы можете установить параметр timeout на более высокое значение.

Сначала необходимо создать новую конечную точку инференции на странице конечных точек Hugging Face, чтобы получить URL конечной точки. Выберите модель all-mpnet-base-v2 на странице создания новой конечной точки, затем выберите задачу Sentence Embeddings в разделе «Дополнительные параметры». Создайте конечную точку. Скопируйте URL после завершения инициализации конечной точки, он необходим для следующего вызова API инференции.

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="hugging_face_embeddings",
    inference_config={
        "service": "hugging_face",
        "service_settings": {
            "api_key": "<access_token>",
            "url": "<url_endpoint>"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "hugging_face_embeddings",
  inference_config: {
    service: "hugging_face",
    service_settings: {
      api_key: "<access_token>",
      url: "<url_endpoint>",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/hugging_face_embeddings 
{
  "service": "hugging_face",
  "service_settings": {
    "api_key": "<access_token>", 
    "url": "<url_endpoint>" 
  }
}

Тип задачи — text_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки инференции, — hugging_face_embeddings.

Действительный токен доступа HuggingFace. Его можно найти на странице настроек вашей учётной записи.

URL конечной точки инференции, созданной вами на Hugging Face.

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="openai_embeddings",
    inference_config={
        "service": "openai",
        "service_settings": {
            "api_key": "<api_key>",
            "model_id": "text-embedding-ada-002"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "openai_embeddings",
  inference_config: {
    service: "openai",
    service_settings: {
      api_key: "<api_key>",
      model_id: "text-embedding-ada-002",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/openai_embeddings 
{
    "service": "openai",
    "service_settings": {
        "api_key": "<api_key>", 
        "model_id": "text-embedding-ada-002" 
    }
}

Тип задачи — text_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки инференции, — openai_embeddings.

Ключ API вашей учётной записи OpenAI. Вы можете найти ключи API OpenAI в своей учётной записи OpenAI в разделе «Ключи API» здесь. Ключ API необходимо указать только один раз. API для получения конечной точки инференции не возвращает ключ API.

Название модели встраивания, которую нужно использовать. Список моделей встраивания OpenAI можно найти здесь.

При использовании этой модели рекомендуется использовать меру сходства dense_vector в поле сопоставления dot_product. В случае с моделями OpenAI векторы встраивания нормализуются до единичной длины, поэтому меры dot_product и cosine эквивалентны.

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="azure_openai_embeddings",
    inference_config={
        "service": "azureopenai",
        "service_settings": {
            "api_key": "<api_key>",
            "resource_name": "<resource_name>",
            "deployment_id": "<deployment_id>",
            "api_version": "2024-02-01"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "azure_openai_embeddings",
  inference_config: {
    service: "azureopenai",
    service_settings: {
      api_key: "<api_key>",
      resource_name: "<resource_name>",
      deployment_id: "<deployment_id>",
      api_version: "2024-02-01",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/azure_openai_embeddings 
{
    "service": "azureopenai",
    "service_settings": {
        "api_key": "<api_key>", 
        "resource_name": "<resource_name>", 
        "deployment_id": "<deployment_id>", 
        "api_version": "2024-02-01"
    }
}

Тип задачи — text_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки инференции, — azure_openai_embeddings.

Ключ API для доступа к вашим службам Azure OpenAI. В качестве альтернативы, вы можете указать entra_id вместо api_key. API для получения конечной точки инференции не возвращает эту информацию.

Имя вашего Azure-ресурса.

Идентификатор развернутой модели.

Развертывание модели может занять несколько минут после её создания. Если вы пытаетесь создать модель как указано выше и получаете сообщение об ошибке 404, подождите несколько минут и повторите попытку. Также при использовании этой модели рекомендуется использовать меру сходства dense_vector в поле сопоставления dot_product. В случае с моделями Azure OpenAI векторы встраивания нормализуются до единичной длины, поэтому меры dot_product и cosine эквивалентны.

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="azure_ai_studio_embeddings",
    inference_config={
        "service": "azureaistudio",
        "service_settings": {
            "api_key": "<api_key>",
            "target": "<target_uri>",
            "provider": "<provider>",
            "endpoint_type": "<endpoint_type>"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "azure_ai_studio_embeddings",
  inference_config: {
    service: "azureaistudio",
    service_settings: {
      api_key: "<api_key>",
      target: "<target_uri>",
      provider: "<provider>",
      endpoint_type: "<endpoint_type>",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/azure_ai_studio_embeddings 
{
    "service": "azureaistudio",
    "service_settings": {
        "api_key": "<api_key>", 
        "target": "<target_uri>", 
        "provider": "<provider>", 
        "endpoint_type": "<endpoint_type>" 
    }
}

Тип задачи — text_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки вывода, равен azure_ai_studio_embeddings.

Ключ API для доступа к развернутой модели Azure AI Studio. Вы можете найти его на странице обзора развертывания модели.

Целевой URI для доступа к развернутой модели Azure AI Studio. Вы можете найти его на странице обзора развертывания модели.

Поставщик модели, например cohere или openai.

Тип развернутой конечной точки. Это может быть token (для развертываний «плати по факту использования»), или realtime для конечных точек развертывания в реальном времени.

Возможно, потребуется несколько минут, чтобы развертывание вашей модели стало доступным после создания. Если вы попытаетесь создать модель как указано выше и получите сообщение об ошибке 404, подождите несколько минут и повторите попытку. Также при использовании этой модели рекомендуется использовать меру сходства dot_product в поле сопоставления dense_vector.

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="google_vertex_ai_embeddings",
    inference_config={
        "service": "googlevertexai",
        "service_settings": {
            "service_account_json": "<service_account_json>",
            "model_id": "text-embedding-004",
            "location": "<location>",
            "project_id": "<project_id>"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "google_vertex_ai_embeddings",
  inference_config: {
    service: "googlevertexai",
    service_settings: {
      service_account_json: "<service_account_json>",
      model_id: "text-embedding-004",
      location: "<location>",
      project_id: "<project_id>",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/google_vertex_ai_embeddings 
{
    "service": "googlevertexai",
    "service_settings": {
        "service_account_json": "<service_account_json>", 
        "model_id": "text-embedding-004", 
        "location": "<location>", 
        "project_id": "<project_id>" 
    }
}

Тип задачи — text_embedding по пути. google_vertex_ai_embeddings — уникальный идентификатор конечной точки вывода (ее inference_id).

Действительный учетная запись сервиса в формате JSON для API Google Vertex AI.

Список доступных моделей можно найти на странице API встраивания текстов.

Имя расположения для использования в задаче вывода. Доступные расположения см. на странице Расположения Generative AI в Vertex AI.

Имя проекта для использования в задаче вывода.

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="mistral_embeddings",
    inference_config={
        "service": "mistral",
        "service_settings": {
            "api_key": "<api_key>",
            "model": "<model_id>"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "mistral_embeddings",
  inference_config: {
    service: "mistral",
    service_settings: {
      api_key: "<api_key>",
      model: "<model_id>",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/mistral_embeddings 
{
    "service": "mistral",
    "service_settings": {
        "api_key": "<api_key>", 
        "model": "<model_id>" 
    }
}

Тип задачи — text_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки вывода, равен mistral_embeddings.

Ключ API для доступа к API Mistral. Вы можете найти его на странице API-ключах в вашем аккаунте Mistral.

Имя модели Mistral для встраивания, например mistral-embed.

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="amazon_bedrock_embeddings",
    inference_config={
        "service": "amazonbedrock",
        "service_settings": {
            "access_key": "<aws_access_key>",
            "secret_key": "<aws_secret_key>",
            "region": "<region>",
            "provider": "<provider>",
            "model": "<model_id>"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "amazon_bedrock_embeddings",
  inference_config: {
    service: "amazonbedrock",
    service_settings: {
      access_key: "<aws_access_key>",
      secret_key: "<aws_secret_key>",
      region: "<region>",
      provider: "<provider>",
      model: "<model_id>",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/amazon_bedrock_embeddings 
{
    "service": "amazonbedrock",
    "service_settings": {
        "access_key": "<aws_access_key>", 
        "secret_key": "<aws_secret_key>", 
        "region": "<region>", 
        "provider": "<provider>", 
        "model": "<model_id>" 
    }
}

Тип задачи — text_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки вывода, равен amazon_bedrock_embeddings.

Ключ доступа можно найти на странице управления AWS IAM для учетной записи пользователя для доступа к Amazon Bedrock.

Секретный ключ должен быть парным ключом для указанного ключа доступа.

Укажите регион, в котором размещена ваша модель.

Укажите поставщика модели.

Идентификатор или ARN модели для использования.

resp = client.inference.put(
    task_type="text_embedding",
    inference_id="alibabacloud_ai_search_embeddings",
    inference_config={
        "service": "alibabacloud-ai-search",
        "service_settings": {
            "api_key": "<api_key>",
            "service_id": "<service_id>",
            "host": "<host>",
            "workspace": "<workspace>"
        }
    },
)
print(resp)
const response = await client.inference.put({
  task_type: "text_embedding",
  inference_id: "alibabacloud_ai_search_embeddings",
  inference_config: {
    service: "alibabacloud-ai-search",
    service_settings: {
      api_key: "<api_key>",
      service_id: "<service_id>",
      host: "<host>",
      workspace: "<workspace>",
    },
  },
});
console.log(response);
PUT _inference/text_embedding/alibabacloud_ai_search_embeddings 
{
    "service": "alibabacloud-ai-search",
    "service_settings": {
        "api_key": "<api_key>", 
        "service_id": "<service_id>", 
        "host": "<host>", 
        "workspace": "<workspace>" 
    }
}

Тип задачи — text_embedding в пути, а inference_id, являющийся уникальным идентификатором конечной точки вывода, равен alibabacloud_ai_search_embeddings.

Ключ API для доступа к API AlibabaCloud AI Search. Вы можете найти свои API-ключи в вашем аккаунте AlibabaCloud в разделе API-ключи. Вам нужно указать свой API-ключ только один раз. API Get inference API не возвращает ваш API-ключ.

Имя модели встраивания AlibabaCloud AI Search, например ops-text-embedding-zh-001.

Имя адреса хоста AlibabaCloud AI Search.

Имя вашей рабочей области AlibabaCloud AI Search.

Создать отображение индекса

Отображение целевого индекса — индекса, содержащего встраивания, которые модель создаст на основе вашего входного текста, — должно быть создано. Целевой индекс должен содержать поле с типом поля dense_vector для большинства моделей и тип поля sparse_vector для моделей разреженных векторов, как в случае с сервисом elasticsearch для индексирования выходных данных используемой модели.

resp = client.indices.create(
    index="cohere-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 1024,
                "element_type": "byte"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'cohere-embeddings',
  body: {
    mappings: {
      properties: {
        content_embedding: {
          type: 'dense_vector',
          dims: 1024,
          element_type: 'byte'
        },
        content: {
          type: 'text'
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "cohere-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 1024,
        element_type: "byte",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT cohere-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 1024, 
        "element_type": "byte"
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Поле, содержащее токены, является полем типа dense_vector.

Размерность вывода модели. Найдите это значение в документации Cohere для используемой модели.

Имя поля, из которого необходимо создать представление плотного вектора. В данном примере имя поля — content. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Тип поля — текст в данном примере.

resp = client.indices.create(
    index="elser-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "sparse_vector"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
const response = await client.indices.create({
  index: "elser-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "sparse_vector",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT elser-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "sparse_vector" 
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Поле, содержащее токены, является полем типа sparse_vector для ELSER.

Имя поля, из которого необходимо создать представление плотного вектора. В данном примере имя поля — content. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Тип поля — текст в данном примере.

resp = client.indices.create(
    index="hugging-face-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 768,
                "element_type": "float"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'hugging-face-embeddings',
  body: {
    mappings: {
      properties: {
        content_embedding: {
          type: 'dense_vector',
          dims: 768,
          element_type: 'float'
        },
        content: {
          type: 'text'
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "hugging-face-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 768,
        element_type: "float",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT hugging-face-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 768, 
        "element_type": "float"
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Поле, содержащее токены, является полем типа dense_vector.

Размерность вывода модели. Найдите это значение в документации HuggingFace модели.

Имя поля, из которого необходимо создать представление плотного вектора. В данном примере имя поля — content. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Тип поля — текст в данном примере.

resp = client.indices.create(
    index="openai-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 1536,
                "element_type": "float",
                "similarity": "dot_product"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'openai-embeddings',
  body: {
    mappings: {
      properties: {
        content_embedding: {
          type: 'dense_vector',
          dims: 1536,
          element_type: 'float',
          similarity: 'dot_product'
        },
        content: {
          type: 'text'
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "openai-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 1536,
        element_type: "float",
        similarity: "dot_product",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT openai-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 1536, 
        "element_type": "float",
        "similarity": "dot_product" 
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Поле, содержащее токены, является полем типа dense_vector.

Размерность вывода модели. Найдите это значение в документации OpenAI для используемой модели.

Функция `dot_product` может быть использована для расчета сходства, поскольку вложения OpenAI нормализованы до единичной длины. Подробнее о выборе функции сходства см. в документации OpenAI.

Имя поля, из которого необходимо создать представление плотного вектора. В данном примере имя поля — content. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Тип поля — текст в данном примере.

resp = client.indices.create(
    index="azure-openai-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 1536,
                "element_type": "float",
                "similarity": "dot_product"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'azure-openai-embeddings',
  body: {
    mappings: {
      properties: {
        content_embedding: {
          type: 'dense_vector',
          dims: 1536,
          element_type: 'float',
          similarity: 'dot_product'
        },
        content: {
          type: 'text'
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "azure-openai-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 1536,
        element_type: "float",
        similarity: "dot_product",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT azure-openai-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 1536, 
        "element_type": "float",
        "similarity": "dot_product" 
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Поле, содержащее токены, является полем типа dense_vector.

Размерность вывода модели. Найдите это значение в документации Azure OpenAI для используемой модели.

Для вложений Azure OpenAI следует использовать функцию dot_product для расчета сходства, так как вложения Azure OpenAI нормализованы до единичной длины. Подробные сведения о спецификациях модели см. в документации Azure OpenAI вложений.

Имя поля, из которого необходимо создать представление плотного вектора. В данном примере имя поля — content. Оно должно быть указано в конфигурации потока вывода на следующем шаге.

Тип поля — текст в данном примере.

resp = client.indices.create(
    index="azure-ai-studio-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 1536,
                "element_type": "float",
                "similarity": "dot_product"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
const response = await client.indices.create({
  index: "azure-ai-studio-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 1536,
        element_type: "float",
        similarity: "dot_product",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT azure-ai-studio-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 1536, 
        "element_type": "float",
        "similarity": "dot_product" 
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Поле, содержащее токены, является полем типа dense_vector.

Размерность выходных данных модели. Это значение можно найти в карточке модели в вашем развертывании Azure AI Studio.

Для встраиваний Azure AI Studio следует использовать функцию dot_product для расчёта сходства.

Имя поля, из которого необходимо создать плотное векторное представление. В данном примере имя поля — content. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Тип поля — текст в этом примере.

resp = client.indices.create(
    index="google-vertex-ai-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 768,
                "element_type": "float",
                "similarity": "dot_product"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
const response = await client.indices.create({
  index: "google-vertex-ai-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 768,
        element_type: "float",
        similarity: "dot_product",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT google-vertex-ai-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 768, 
        "element_type": "float",
        "similarity": "dot_product" 
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные встраивания. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Поле, содержащее встраивания, является полем типа dense_vector.

Размерность выходных данных модели. Это значение можно найти на странице справочной информации о моделях Google Vertex AI. API вывода пытается автоматически рассчитать размерность выходных данных, если значения dims не указаны.

Для встраиваний Google Vertex AI следует использовать функцию dot_product для расчёта сходства.

Имя поля, из которого необходимо создать плотное векторное представление. В данном примере имя поля — content. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Тип поля — text в этом примере.

resp = client.indices.create(
    index="mistral-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 1024,
                "element_type": "float",
                "similarity": "dot_product"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
const response = await client.indices.create({
  index: "mistral-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 1024,
        element_type: "float",
        similarity: "dot_product",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT mistral-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 1024, 
        "element_type": "float",
        "similarity": "dot_product" 
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Поле, содержащее токены, является полем типа dense_vector.

Размерность выходных данных модели. Это значение можно найти на странице с описанием моделей Mistral.

Для встраиваний Mistral следует использовать функцию dot_product для расчёта сходства.

Имя поля, из которого необходимо создать плотное векторное представление. В данном примере имя поля — content. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Тип поля — текст в этом примере.

resp = client.indices.create(
    index="amazon-bedrock-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 1024,
                "element_type": "float",
                "similarity": "dot_product"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
const response = await client.indices.create({
  index: "amazon-bedrock-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 1024,
        element_type: "float",
        similarity: "dot_product",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT amazon-bedrock-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 1024, 
        "element_type": "float",
        "similarity": "dot_product" 
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Поле, содержащее токены, является полем типа dense_vector.

Размерность выходных данных модели может отличаться в зависимости от используемой модели. См. документацию модели Amazon Titan или модели встраиваний Cohere.

Для встраиваний Amazon Bedrock следует использовать функцию dot_product для расчёта сходства для моделей Amazon Titan или cosine для моделей Cohere.

Имя поля, из которого необходимо создать плотное векторное представление. В данном примере имя поля — content. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Тип поля — текст в этом примере.

resp = client.indices.create(
    index="alibabacloud-ai-search-embeddings",
    mappings={
        "properties": {
            "content_embedding": {
                "type": "dense_vector",
                "dims": 1024,
                "element_type": "float"
            },
            "content": {
                "type": "text"
            }
        }
    },
)
print(resp)
const response = await client.indices.create({
  index: "alibabacloud-ai-search-embeddings",
  mappings: {
    properties: {
      content_embedding: {
        type: "dense_vector",
        dims: 1024,
        element_type: "float",
      },
      content: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT alibabacloud-ai-search-embeddings
{
  "mappings": {
    "properties": {
      "content_embedding": { 
        "type": "dense_vector", 
        "dims": 1024, 
        "element_type": "float"
      },
      "content": { 
        "type": "text" 
      }
    }
  }
}

Имя поля, содержащего сгенерированные токены. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Поле, содержащее токены, является полем типа dense_vector.

Размерность выходных данных модели может отличаться в зависимости от используемой модели. См. документацию модели встраиваний AlibabaCloud AI Search.

Имя поля, из которого необходимо создать плотное векторное представление. В данном примере имя поля — content. Оно должно быть указано в конфигурации конвейера вывода на следующем шаге.

Тип поля — текст в этом примере.

Создайте конвейер загрузки с процессором вывода

Создайте конвейер загрузки с процессором вывода и используйте созданную выше модель для вывода данных, загружаемых в конвейер.

resp = client.ingest.put_pipeline(
    id="cohere_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "cohere_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "cohere_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "cohere_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/cohere_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "cohere_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="elser_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "elser_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "elser_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "elser_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/elser_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "elser_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="hugging_face_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "hugging_face_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "hugging_face_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "hugging_face_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/hugging_face_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "hugging_face_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="openai_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "openai_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "openai_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "openai_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/openai_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "openai_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="azure_openai_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "azure_openai_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "azure_openai_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "azure_openai_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/azure_openai_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "azure_openai_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="azure_ai_studio_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "azure_ai_studio_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "azure_ai_studio_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "azure_ai_studio_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/azure_ai_studio_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "azure_ai_studio_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="google_vertex_ai_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "google_vertex_ai_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "google_vertex_ai_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "google_vertex_ai_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/google_vertex_ai_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "google_vertex_ai_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="mistral_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "mistral_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "mistral_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "mistral_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/mistral_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "mistral_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="amazon_bedrock_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "amazon_bedrock_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "amazon_bedrock_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "amazon_bedrock_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/amazon_bedrock_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "amazon_bedrock_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, созданной с помощью Create inference API, она упоминается как inference_id на этом этапе.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

resp = client.ingest.put_pipeline(
    id="alibabacloud_ai_search_embeddings_pipeline",
    processors=[
        {
            "inference": {
                "model_id": "alibabacloud_ai_search_embeddings",
                "input_output": {
                    "input_field": "content",
                    "output_field": "content_embedding"
                }
            }
        }
    ],
)
print(resp)
const response = await client.ingest.putPipeline({
  id: "alibabacloud_ai_search_embeddings_pipeline",
  processors: [
    {
      inference: {
        model_id: "alibabacloud_ai_search_embeddings",
        input_output: {
          input_field: "content",
          output_field: "content_embedding",
        },
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/alibabacloud_ai_search_embeddings_pipeline
{
  "processors": [
    {
      "inference": {
        "model_id": "alibabacloud_ai_search_embeddings", 
        "input_output": { 
          "input_field": "content",
          "output_field": "content_embedding"
        }
      }
    }
  ]
}

Имя конечной точки вывода, которое вы создали с помощью создания API вывода, в данном шаге она упоминается как inference_id.

Объект конфигурации, определяющий input_field для процесса вывода и output_field, который будет содержать результаты вывода.

Загрузка данных

На этом шаге вы загружаете данные, которые затем используются в конвейере вывода для создания эмбеддингов.

Используйте набор данных msmarco-passagetest2019-top1000, который является подмножеством набора данных MS MARCO Passage Ranking. Он состоит из 200 запросов, каждый из которых сопровождается списком соответствующих текстовых фрагментов. Все уникальные фрагменты вместе с их идентификаторами были извлечены из этого набора данных и скомпилированы в tsv файл.

Загрузите файл и загрузите его в свой кластер, используя Визуализатор данных в пользовательском интерфейсе Machine Learning. После анализа данных нажмите Переопределить настройки. В разделе Изменить имена полей назначьте id первому столбцу и content второму. Нажмите Применить, а затем Импортировать. Назовите индекс test-data и нажмите Импортировать. После завершения загрузки вы увидите индекс под названием test-data с 182 469 документами.

Обработка данных через конвейер вывода

Создайте эмбеддинги из текста, переиндексировав данные через конвейер вывода, использующий выбранную модель. На этом шаге используется API переиндексации для моделирования загрузки данных через конвейер.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "cohere-embeddings",
        "pipeline": "cohere_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "cohere-embeddings",
    pipeline: "cohere_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "cohere-embeddings",
    "pipeline": "cohere_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

Лимит скорости вашей учетной записи Cohere может повлиять на производительность процесса переиндексации.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "elser-embeddings",
        "pipeline": "elser_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "elser-embeddings",
    pipeline: "elser_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "elser-embeddings",
    "pipeline": "elser_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "hugging-face-embeddings",
        "pipeline": "hugging_face_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "hugging-face-embeddings",
    pipeline: "hugging_face_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "hugging-face-embeddings",
    "pipeline": "hugging_face_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "openai-embeddings",
        "pipeline": "openai_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "openai-embeddings",
    pipeline: "openai_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "openai-embeddings",
    "pipeline": "openai_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

Лимит скорости вашей учетной записи OpenAI может повлиять на производительность процесса переиндексации. В этом случае измените size на 3 или на аналогичное по порядку величины значение.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "azure-openai-embeddings",
        "pipeline": "azure_openai_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "azure-openai-embeddings",
    pipeline: "azure_openai_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "azure-openai-embeddings",
    "pipeline": "azure_openai_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

Лимит скорости вашей учетной записи Azure OpenAI может повлиять на производительность процесса переиндексации. В этом случае измените size на 3 или на аналогичное по порядку величины значение.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "azure-ai-studio-embeddings",
        "pipeline": "azure_ai_studio_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "azure-ai-studio-embeddings",
    pipeline: "azure_ai_studio_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "azure-ai-studio-embeddings",
    "pipeline": "azure_ai_studio_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

Развертывание вашей модели Azure AI Studio может иметь ограничения скорости, которые могут повлиять на производительность процесса переиндексации. В этом случае измените size на 3 или на аналогичное по порядку величины значение.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "google-vertex-ai-embeddings",
        "pipeline": "google_vertex_ai_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "google-vertex-ai-embeddings",
    pipeline: "google_vertex_ai_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "google-vertex-ai-embeddings",
    "pipeline": "google_vertex_ai_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size ускорит обновления процесса переиндексации. Это позволит отслеживать ход выполнения и своевременно выявлять ошибки.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "mistral-embeddings",
        "pipeline": "mistral_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "mistral-embeddings",
    pipeline: "mistral_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "mistral-embeddings",
    "pipeline": "mistral_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "amazon-bedrock-embeddings",
        "pipeline": "amazon_bedrock_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "amazon-bedrock-embeddings",
    pipeline: "amazon_bedrock_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "amazon-bedrock-embeddings",
    "pipeline": "amazon_bedrock_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

resp = client.reindex(
    wait_for_completion=False,
    source={
        "index": "test-data",
        "size": 50
    },
    dest={
        "index": "alibabacloud-ai-search-embeddings",
        "pipeline": "alibabacloud_ai_search_embeddings_pipeline"
    },
)
print(resp)
const response = await client.reindex({
  wait_for_completion: "false",
  source: {
    index: "test-data",
    size: 50,
  },
  dest: {
    index: "alibabacloud-ai-search-embeddings",
    pipeline: "alibabacloud_ai_search_embeddings_pipeline",
  },
});
console.log(response);
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "test-data",
    "size": 50 
  },
  "dest": {
    "index": "alibabacloud-ai-search-embeddings",
    "pipeline": "alibabacloud_ai_search_embeddings_pipeline"
  }
}

Размер пакета по умолчанию для переиндексации — 1000. Уменьшение size до меньшего значения ускорит обновление процесса переиндексации, что позволит отслеживать ход выполнения и своевременно выявлять ошибки.

Вызов возвращает ID задачи для отслеживания хода выполнения:

resp = client.tasks.get(
    task_id="<task_id>",
)
print(resp)
const response = await client.tasks.get({
  task_id: "<task_id>",
});
console.log(response);
GET _tasks/<task_id>

Переиндексация больших наборов данных может занять много времени. Вы можете протестировать этот рабочий процесс, используя только подмножество набора данных. Сделайте это, отменив процесс переиндексации и сгенерировав вложения только для переиндексированного подмножества. Следующий API-запрос отменит задачу переиндексации:

resp = client.tasks.cancel(
    task_id="<task_id>",
)
print(resp)
const response = await client.tasks.cancel({
  task_id: "<task_id>",
});
console.log(response);
POST _tasks/<task_id>/_cancel

Семантический поиск

После того, как набор данных был обогащен вложениями, вы можете запрашивать данные с помощью семантического поиска. В случае плотных векторных моделей передайте query_vector_builder в API поиска вектора k-ближайших соседей (kNN) и укажите текст запроса и модель, которую вы использовали для создания вложений. В случае разреженной векторной модели, такой как ELSER, используйте запрос sparse_vector и укажите текст запроса с моделью, которую вы использовали для создания вложений.

Если вы отменили процесс переиндексации, вы выполняете запрос только для части данных, что влияет на качество ваших результатов.

resp = client.search(
    index="cohere-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "cohere_embeddings",
                "model_text": "Muscles in human body"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
response = client.search(
  index: 'cohere-embeddings',
  body: {
    knn: {
      field: 'content_embedding',
      query_vector_builder: {
        text_embedding: {
          model_id: 'cohere_embeddings',
          model_text: 'Muscles in human body'
        }
      },
      k: 10,
      num_candidates: 100
    },
    _source: [
      'id',
      'content'
    ]
  }
)
puts response
const response = await client.search({
  index: "cohere-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "cohere_embeddings",
        model_text: "Muscles in human body",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET cohere-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "cohere_embeddings",
        "model_text": "Muscles in human body"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса cohere-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "cohere-embeddings",
        "_id": "-eFWCY4BECzWLnMZuI78",
        "_score": 0.737484,
        "_source": {
          "id": 1690948,
          "content": "Oxygen is supplied to the muscles via red blood cells. Red blood cells carry hemoglobin which oxygen bonds with as the hemoglobin rich blood cells pass through the blood vessels of the lungs.The now oxygen rich blood cells carry that oxygen to the cells that are demanding it, in this case skeletal muscle cells.ther ways in which muscles are supplied with oxygen include: 1  Blood flow from the heart is increased. 2  Blood flow to your muscles in increased. 3  Blood flow from nonessential organs is transported to working muscles."
        }
      },
      {
        "_index": "cohere-embeddings",
        "_id": "HuFWCY4BECzWLnMZuI_8",
        "_score": 0.7176013,
        "_source": {
          "id": 1692482,
          "content": "The thoracic cavity is separated from the abdominal cavity by the  diaphragm. This is a broad flat muscle.    (muscular) diaphragm The diaphragm is a muscle that separat…e the thoracic from the abdominal cavity. The pelvis is the lowest part of the abdominal cavity and it has no physical separation from it    Diaphragm."
        }
      },
      {
        "_index": "cohere-embeddings",
        "_id": "IOFWCY4BECzWLnMZuI_8",
        "_score": 0.7154432,
        "_source": {
          "id": 1692489,
          "content": "Muscular Wall Separating the Abdominal and Thoracic Cavities; Thoracic Cavity of a Fetal Pig; In Mammals the Diaphragm Separates the Abdominal Cavity from the"
        }
      },
      {
        "_index": "cohere-embeddings",
        "_id": "C-FWCY4BECzWLnMZuI_8",
        "_score": 0.695313,
        "_source": {
          "id": 1691493,
          "content": "Burning, aching, tenderness and stiffness are just some descriptors of the discomfort you may feel in the muscles you exercised one to two days ago.For the most part, these sensations you experience after exercise are collectively known as delayed onset muscle soreness.urning, aching, tenderness and stiffness are just some descriptors of the discomfort you may feel in the muscles you exercised one to two days ago."
        }
      },
      (...)
    ]
resp = client.search(
    index="elser-embeddings",
    query={
        "sparse_vector": {
            "field": "content_embedding",
            "inference_id": "elser_embeddings",
            "query": "How to avoid muscle soreness after running?"
        }
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
const response = await client.search({
  index: "elser-embeddings",
  query: {
    sparse_vector: {
      field: "content_embedding",
      inference_id: "elser_embeddings",
      query: "How to avoid muscle soreness after running?",
    },
  },
  _source: ["id", "content"],
});
console.log(response);
GET elser-embeddings/_search
{
  "query":{
    "sparse_vector":{
      "field": "content_embedding",
      "inference_id": "elser_embeddings",
      "query": "How to avoid muscle soreness after running?"
    }
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса cohere-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "elser-embeddings",
        "_id": "ZLGc_pABZbBmsu5_eCoH",
        "_score": 21.472063,
        "_source": {
          "id": 2258240,
          "content": "You may notice some muscle aches while you are exercising. This is called acute soreness. More often, you may begin to feel sore about 12 hours after exercising, and the discomfort usually peaks at 48 to 72 hours after exercise. This is called delayed-onset muscle soreness.It is thought that, during this time, your body is repairing the muscle, making it stronger and bigger.You may also notice the muscles feel better if you exercise lightly. This is normal.his is called delayed-onset muscle soreness. It is thought that, during this time, your body is repairing the muscle, making it stronger and bigger. You may also notice the muscles feel better if you exercise lightly. This is normal."
        }
      },
      {
        "_index": "elser-embeddings",
        "_id": "ZbGc_pABZbBmsu5_eCoH",
        "_score": 21.421381,
        "_source": {
          "id": 2258242,
          "content": "Photo Credit Jupiterimages/Stockbyte/Getty Images. That stiff, achy feeling you get in the days after exercise is a normal physiological response known as delayed onset muscle soreness. You can take it as a positive sign that your muscles have felt the workout, but the pain may also turn you off to further exercise.ou are more likely to develop delayed onset muscle soreness if you are new to working out, if you’ve gone a long time without exercising and start up again, if you have picked up a new type of physical activity or if you have recently boosted the intensity, length or frequency of your exercise sessions."
        }
      },
      {
        "_index": "elser-embeddings",
        "_id": "ZrGc_pABZbBmsu5_eCoH",
        "_score": 20.542095,
        "_source": {
          "id": 2258248,
          "content": "They found that stretching before and after exercise has no effect on muscle soreness. Exercise might cause inflammation, which leads to an increase in the production of immune cells (comprised mostly of macrophages and neutrophils). Levels of these immune cells reach a peak 24-48 hours after exercise.These cells, in turn, produce bradykinins and prostaglandins, which make the pain receptors in your body more sensitive. Whenever you move, these pain receptors are stimulated.hey found that stretching before and after exercise has no effect on muscle soreness. Exercise might cause inflammation, which leads to an increase in the production of immune cells (comprised mostly of macrophages and neutrophils). Levels of these immune cells reach a peak 24-48 hours after exercise."
        }
      },
    (...)
  ]
resp = client.search(
    index="hugging-face-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "hugging_face_embeddings",
                "model_text": "What's margin of error?"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
response = client.search(
  index: 'hugging-face-embeddings',
  body: {
    knn: {
      field: 'content_embedding',
      query_vector_builder: {
        text_embedding: {
          model_id: 'hugging_face_embeddings',
          model_text: "What's margin of error?"
        }
      },
      k: 10,
      num_candidates: 100
    },
    _source: [
      'id',
      'content'
    ]
  }
)
puts response
const response = await client.search({
  index: "hugging-face-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "hugging_face_embeddings",
        model_text: "What's margin of error?",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET hugging-face-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "hugging_face_embeddings",
        "model_text": "What's margin of error?"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса hugging-face-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "hugging-face-embeddings",
        "_id": "ljEfo44BiUQvMpPgT20E",
        "_score": 0.8522128,
        "_source": {
          "id": 7960255,
          "content": "The margin of error can be defined by either of the following equations. Margin of error = Critical value x Standard deviation of the statistic. Margin of error = Critical value x Standard error of the statistic. If you know the standard deviation of the statistic, use the first equation to compute the margin of error. Otherwise, use the second equation. Previously, we described how to compute the standard deviation and standard error."
        }
      },
      {
        "_index": "hugging-face-embeddings",
        "_id": "lzEfo44BiUQvMpPgT20E",
        "_score": 0.7865497,
        "_source": {
          "id": 7960259,
          "content": "1 y ou are told only the size of the sample and are asked to provide the margin of error for percentages which are not (yet) known. 2  This is typically the case when you are computing the margin of error for a survey which is going to be conducted in the future."
        }
      },
      {
        "_index": "hugging-face-embeddings1",
        "_id": "DjEfo44BiUQvMpPgT20E",
        "_score": 0.6229427,
        "_source": {
          "id": 2166183,
          "content": "1. In general, the point at which gains equal losses. 2. In options, the market price that a stock must reach for option buyers to avoid a loss if they exercise. For a call, it is the strike price plus the premium paid. For a put, it is the strike price minus the premium paid."
        }
      },
      {
        "_index": "hugging-face-embeddings1",
        "_id": "VzEfo44BiUQvMpPgT20E",
        "_score": 0.6034223,
        "_source": {
          "id": 2173417,
          "content": "How do you find the area of a circle? Can you measure the area of a circle and use that to find a value for Pi?"
        }
      },
      (...)
    ]
resp = client.search(
    index="openai-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "openai_embeddings",
                "model_text": "Calculate fuel cost"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
response = client.search(
  index: 'openai-embeddings',
  body: {
    knn: {
      field: 'content_embedding',
      query_vector_builder: {
        text_embedding: {
          model_id: 'openai_embeddings',
          model_text: 'Calculate fuel cost'
        }
      },
      k: 10,
      num_candidates: 100
    },
    _source: [
      'id',
      'content'
    ]
  }
)
puts response
const response = await client.search({
  index: "openai-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "openai_embeddings",
        model_text: "Calculate fuel cost",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET openai-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "openai_embeddings",
        "model_text": "Calculate fuel cost"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса openai-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "openai-embeddings",
        "_id": "DDd5OowBHxQKHyc3TDSC",
        "_score": 0.83704096,
        "_source": {
          "id": 862114,
          "body": "How to calculate fuel cost for a road trip. By Tara Baukus Mello • Bankrate.com. Dear Driving for Dollars, My family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost.It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes.y family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost. It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes."
        }
      },
      {
        "_index": "openai-embeddings",
        "_id": "ajd5OowBHxQKHyc3TDSC",
        "_score": 0.8345704,
        "_source": {
          "id": 820622,
          "body": "Home Heating Calculator. Typically, approximately 50% of the energy consumed in a home annually is for space heating. When deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important.This calculator can help you estimate the cost of fuel for different heating appliances.hen deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important. This calculator can help you estimate the cost of fuel for different heating appliances."
        }
      },
      {
        "_index": "openai-embeddings",
        "_id": "Djd5OowBHxQKHyc3TDSC",
        "_score": 0.8327426,
        "_source": {
          "id": 8202683,
          "body": "Fuel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel.If you are paying $4 per gallon, the trip would cost you $200.Most boats have much larger gas tanks than cars.uel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel."
        }
      },
      (...)
    ]
resp = client.search(
    index="azure-openai-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "azure_openai_embeddings",
                "model_text": "Calculate fuel cost"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
response = client.search(
  index: 'azure-openai-embeddings',
  body: {
    knn: {
      field: 'content_embedding',
      query_vector_builder: {
        text_embedding: {
          model_id: 'azure_openai_embeddings',
          model_text: 'Calculate fuel cost'
        }
      },
      k: 10,
      num_candidates: 100
    },
    _source: [
      'id',
      'content'
    ]
  }
)
puts response
const response = await client.search({
  index: "azure-openai-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "azure_openai_embeddings",
        model_text: "Calculate fuel cost",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET azure-openai-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "azure_openai_embeddings",
        "model_text": "Calculate fuel cost"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса azure-openai-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "azure-openai-embeddings",
        "_id": "DDd5OowBHxQKHyc3TDSC",
        "_score": 0.83704096,
        "_source": {
          "id": 862114,
          "body": "How to calculate fuel cost for a road trip. By Tara Baukus Mello • Bankrate.com. Dear Driving for Dollars, My family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost.It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes.y family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost. It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes."
        }
      },
      {
        "_index": "azure-openai-embeddings",
        "_id": "ajd5OowBHxQKHyc3TDSC",
        "_score": 0.8345704,
        "_source": {
          "id": 820622,
          "body": "Home Heating Calculator. Typically, approximately 50% of the energy consumed in a home annually is for space heating. When deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important.This calculator can help you estimate the cost of fuel for different heating appliances.hen deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important. This calculator can help you estimate the cost of fuel for different heating appliances."
        }
      },
      {
        "_index": "azure-openai-embeddings",
        "_id": "Djd5OowBHxQKHyc3TDSC",
        "_score": 0.8327426,
        "_source": {
          "id": 8202683,
          "body": "Fuel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel.If you are paying $4 per gallon, the trip would cost you $200.Most boats have much larger gas tanks than cars.uel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel."
        }
      },
      (...)
    ]
resp = client.search(
    index="azure-ai-studio-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "azure_ai_studio_embeddings",
                "model_text": "Calculate fuel cost"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
const response = await client.search({
  index: "azure-ai-studio-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "azure_ai_studio_embeddings",
        model_text: "Calculate fuel cost",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET azure-ai-studio-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "azure_ai_studio_embeddings",
        "model_text": "Calculate fuel cost"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса azure-ai-studio-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "azure-ai-studio-embeddings",
        "_id": "DDd5OowBHxQKHyc3TDSC",
        "_score": 0.83704096,
        "_source": {
          "id": 862114,
          "body": "How to calculate fuel cost for a road trip. By Tara Baukus Mello • Bankrate.com. Dear Driving for Dollars, My family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost.It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes.y family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost. It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes."
        }
      },
      {
        "_index": "azure-ai-studio-embeddings",
        "_id": "ajd5OowBHxQKHyc3TDSC",
        "_score": 0.8345704,
        "_source": {
          "id": 820622,
          "body": "Home Heating Calculator. Typically, approximately 50% of the energy consumed in a home annually is for space heating. When deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important.This calculator can help you estimate the cost of fuel for different heating appliances.hen deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important. This calculator can help you estimate the cost of fuel for different heating appliances."
        }
      },
      {
        "_index": "azure-ai-studio-embeddings",
        "_id": "Djd5OowBHxQKHyc3TDSC",
        "_score": 0.8327426,
        "_source": {
          "id": 8202683,
          "body": "Fuel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel.If you are paying $4 per gallon, the trip would cost you $200.Most boats have much larger gas tanks than cars.uel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel."
        }
      },
      (...)
    ]
resp = client.search(
    index="google-vertex-ai-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "google_vertex_ai_embeddings",
                "model_text": "Calculate fuel cost"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
const response = await client.search({
  index: "google-vertex-ai-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "google_vertex_ai_embeddings",
        model_text: "Calculate fuel cost",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET google-vertex-ai-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "google_vertex_ai_embeddings",
        "model_text": "Calculate fuel cost"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса mistral-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "google-vertex-ai-embeddings",
        "_id": "Ryv0nZEBBFPLbFsdCbGn",
        "_score": 0.86815524,
        "_source": {
          "id": 3041038,
          "content": "For example, the cost of the fuel could be 96.9, the amount could be 10 pounds, and the distance covered could be 80 miles. To convert between Litres per 100KM and Miles Per Gallon, please provide a value and click on the required button.o calculate how much fuel you'll need for a given journey, please provide the distance in miles you will be covering on your journey, and the estimated MPG of your vehicle. To work out what MPG you are really getting, please provide the cost of the fuel, how much you spent on the fuel, and how far it took you."
        }
      },
      {
        "_index": "google-vertex-ai-embeddings",
        "_id": "w4j0nZEBZ1nFq1oiHQvK",
        "_score": 0.8676357,
        "_source": {
          "id": 1541469,
          "content": "This driving cost calculator takes into consideration the fuel economy of the vehicle that you are travelling in as well as the fuel cost. This road trip gas calculator will give you an idea of how much would it cost to drive before you actually travel.his driving cost calculator takes into consideration the fuel economy of the vehicle that you are travelling in as well as the fuel cost. This road trip gas calculator will give you an idea of how much would it cost to drive before you actually travel."
        }
      },
      {
        "_index": "google-vertex-ai-embeddings",
        "_id": "Hoj0nZEBZ1nFq1oiHQjJ",
        "_score": 0.80510974,
        "_source": {
          "id": 7982559,
          "content": "What's that light cost you? 1  Select your electric rate (or click to enter your own). 2  You can calculate results for up to four types of lights. 3  Select the type of lamp (i.e. 4  Select the lamp wattage (lamp lumens). 5  Enter the number of lights in use. 6  Select how long the lamps are in use (or click to enter your own; enter hours on per year). 7  Finally, ..."
        }
      },
      (...)
    ]
resp = client.search(
    index="mistral-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "mistral_embeddings",
                "model_text": "Calculate fuel cost"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
const response = await client.search({
  index: "mistral-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "mistral_embeddings",
        model_text: "Calculate fuel cost",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET mistral-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "mistral_embeddings",
        "model_text": "Calculate fuel cost"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса mistral-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "mistral-embeddings",
        "_id": "DDd5OowBHxQKHyc3TDSC",
        "_score": 0.83704096,
        "_source": {
          "id": 862114,
          "body": "How to calculate fuel cost for a road trip. By Tara Baukus Mello • Bankrate.com. Dear Driving for Dollars, My family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost.It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes.y family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost. It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes."
        }
      },
      {
        "_index": "mistral-embeddings",
        "_id": "ajd5OowBHxQKHyc3TDSC",
        "_score": 0.8345704,
        "_source": {
          "id": 820622,
          "body": "Home Heating Calculator. Typically, approximately 50% of the energy consumed in a home annually is for space heating. When deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important.This calculator can help you estimate the cost of fuel for different heating appliances.hen deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important. This calculator can help you estimate the cost of fuel for different heating appliances."
        }
      },
      {
        "_index": "mistral-embeddings",
        "_id": "Djd5OowBHxQKHyc3TDSC",
        "_score": 0.8327426,
        "_source": {
          "id": 8202683,
          "body": "Fuel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel.If you are paying $4 per gallon, the trip would cost you $200.Most boats have much larger gas tanks than cars.uel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel."
        }
      },
      (...)
    ]
resp = client.search(
    index="amazon-bedrock-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "amazon_bedrock_embeddings",
                "model_text": "Calculate fuel cost"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
const response = await client.search({
  index: "amazon-bedrock-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "amazon_bedrock_embeddings",
        model_text: "Calculate fuel cost",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET amazon-bedrock-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "amazon_bedrock_embeddings",
        "model_text": "Calculate fuel cost"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса amazon-bedrock-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "amazon-bedrock-embeddings",
        "_id": "DDd5OowBHxQKHyc3TDSC",
        "_score": 0.83704096,
        "_source": {
          "id": 862114,
          "body": "How to calculate fuel cost for a road trip. By Tara Baukus Mello • Bankrate.com. Dear Driving for Dollars, My family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost.It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes.y family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost. It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes."
        }
      },
      {
        "_index": "amazon-bedrock-embeddings",
        "_id": "ajd5OowBHxQKHyc3TDSC",
        "_score": 0.8345704,
        "_source": {
          "id": 820622,
          "body": "Home Heating Calculator. Typically, approximately 50% of the energy consumed in a home annually is for space heating. When deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important.This calculator can help you estimate the cost of fuel for different heating appliances.hen deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important. This calculator can help you estimate the cost of fuel for different heating appliances."
        }
      },
      {
        "_index": "amazon-bedrock-embeddings",
        "_id": "Djd5OowBHxQKHyc3TDSC",
        "_score": 0.8327426,
        "_source": {
          "id": 8202683,
          "body": "Fuel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel.If you are paying $4 per gallon, the trip would cost you $200.Most boats have much larger gas tanks than cars.uel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel."
        }
      },
      (...)
    ]
resp = client.search(
    index="alibabacloud-ai-search-embeddings",
    knn={
        "field": "content_embedding",
        "query_vector_builder": {
            "text_embedding": {
                "model_id": "alibabacloud_ai_search_embeddings",
                "model_text": "Calculate fuel cost"
            }
        },
        "k": 10,
        "num_candidates": 100
    },
    source=[
        "id",
        "content"
    ],
)
print(resp)
const response = await client.search({
  index: "alibabacloud-ai-search-embeddings",
  knn: {
    field: "content_embedding",
    query_vector_builder: {
      text_embedding: {
        model_id: "alibabacloud_ai_search_embeddings",
        model_text: "Calculate fuel cost",
      },
    },
    k: 10,
    num_candidates: 100,
  },
  _source: ["id", "content"],
});
console.log(response);
GET alibabacloud-ai-search-embeddings/_search
{
  "knn": {
    "field": "content_embedding",
    "query_vector_builder": {
      "text_embedding": {
        "model_id": "alibabacloud_ai_search_embeddings",
        "model_text": "Calculate fuel cost"
      }
    },
    "k": 10,
    "num_candidates": 100
  },
  "_source": [
    "id",
    "content"
  ]
}

В результате вы получите 10 лучших документов, наиболее близких по смыслу к запросу из индекса alibabacloud-ai-search-embeddings, отсортированных по близости к запросу:

"hits": [
      {
        "_index": "alibabacloud-ai-search-embeddings",
        "_id": "DDd5OowBHxQKHyc3TDSC",
        "_score": 0.83704096,
        "_source": {
          "id": 862114,
          "body": "How to calculate fuel cost for a road trip. By Tara Baukus Mello • Bankrate.com. Dear Driving for Dollars, My family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost.It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes.y family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost. It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes."
        }
      },
      {
        "_index": "alibabacloud-ai-search-embeddings",
        "_id": "ajd5OowBHxQKHyc3TDSC",
        "_score": 0.8345704,
        "_source": {
          "id": 820622,
          "body": "Home Heating Calculator. Typically, approximately 50% of the energy consumed in a home annually is for space heating. When deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important.This calculator can help you estimate the cost of fuel for different heating appliances.hen deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important. This calculator can help you estimate the cost of fuel for different heating appliances."
        }
      },
      {
        "_index": "alibabacloud-ai-search-embeddings",
        "_id": "Djd5OowBHxQKHyc3TDSC",
        "_score": 0.8327426,
        "_source": {
          "id": 8202683,
          "body": "Fuel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel.If you are paying $4 per gallon, the trip would cost you $200.Most boats have much larger gas tanks than cars.uel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel."
        }
      },
      (...)
    ]

Интерактивные руководства

Вы также можете найти руководства в интерактивном формате записной книжки Colab, используя клиент Elasticsearch Python:

  • Записная книжка с руководством по выводу Cohere
  • Записная книжка с руководством по выводу OpenAI

© 2023-2025 Elasticsearch
As of September 2024, Elasticsearch is available under a choice of three licenses: the Server Side Public License (SSPL), the Elastic License, or the AGPLv3 (OSI approved).
Elasticsearch and the Elasticsearch logo are trademarks of Elasticsearch B.V., registered in the U.S. and in other countries.
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/semantic-search-inference.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API