Compartilhar via


Início Rápido: Busca em vetores usando REST

Saiba como usar as APIs REST de pesquisa para criar, carregar e consultar vetores na Pesquisa de IA do Azure.

Na Pesquisa de IA do Azure, um repositório de vetores tem um esquema de índice que define campos vetoriais e não vetoriais, uma configuração de busca em vetores para algoritmos que criam o espaço de inserção e configurações em definições de campo de vetor que são avaliadas no momento da consulta. A API REST Criar Índice cria o repositório de vetores.

Se você não tiver uma assinatura do Azure, crie uma conta gratuita antes de começar.

Observação

Este início rápido omite a etapa de vetorização e fornece inserções em documentos de amostra. Se você quiser adicionar agrupamento de dados e vetorização internos ao seu próprio conteúdo, experimente o assistente Importar e vetorizar dados para um guia completo passo a passo.

Pré-requisitos

Recuperar as informações do recurso

As solicitações para o ponto de extremidade de pesquisa precisam ser autenticadas e autorizadas. Você pode usar funções ou chaves de API para essa tarefa. É recomendável usar uma conexão sem chave por meio do Microsoft Entra ID.

Selecione a guia que corresponde ao método de autenticação preferencial. Use o mesmo método para todas as solicitações neste início rápido.

  1. Entre no portal do Azure e localize o serviço de pesquisa.

  2. Na página inicial Visão Geral, encontre a URL. Um ponto de extremidade de exemplo pode parecer com https://mydemo.search.windows.net.

    Captura de tela de propriedades de URL na página de visão geral.

  3. Siga as etapas no início rápido sem chave para obter o token do Microsoft Entra.

    Você obtém o token quando executa o comando az account get-access-token na etapa 3 do início rápido anterior.

    az account get-access-token --scope https://search.azure.com/.default --query accessToken --output tsv
    

Criar ou baixar o arquivo de código

Você usa um arquivo .rest ou .http para executar todas as solicitações neste início rápido. Você pode baixar o arquivo REST que contém o código deste início rápido ou criar um novo arquivo no Visual Studio Code e copiar o código para ele.

  1. No Visual Studio Code, crie um novo arquivo com uma extensão de arquivo .rest ou .http. Por exemplo, az-search-vector-quickstart.rest. Copie e cole o conteúdo bruto do arquivo Azure-Samples/azure-search-rest-samples/blob/main/Quickstart-vectors/az-search-vector-quickstart.rest neste novo arquivo.

  2. Na parte superior do arquivo, substitua o valor do espaço reservado por @baseUrl com a URL do serviço de pesquisa. Confira a seção Recuperar informações do recurso para obter instruções sobre como localizar a URL do serviço de pesquisa.

    @baseUrl = PUT-YOUR-SEARCH-SERVICE-URL-HERE
    
  3. Na parte superior do arquivo, substitua o valor do espaço reservado para autenticação. Confira a seção Recuperar informações de recursos para obter instruções sobre como obter o seu token ou chave de API do Microsoft Entra.

    Para a autenticação sem chave recomendada por meio do Microsoft Entra ID, você precisa substituir @apiKey pela variável @token.

    @token = PUT-YOUR-MICROSOFT-ENTRA-TOKEN-HERE
    

    Se preferir usar uma chave de API, substitua @apiKey pela chave copiada do portal do Azure.

    @apiKey = PUT-YOUR-ADMIN-KEY-HERE
    
  4. Para a autenticação sem chave recomendada por meio do Microsoft Entra ID, você precisa substituir api-key: {{apiKey}} por Authorization: Bearer {{token}} nos cabeçalhos de solicitação. Substitua todas as instâncias de api-key: {{apiKey}} que você encontrar no arquivo.

Criar um índice de vetor

Use a API REST Criar Índice para criar um índice de vetor e configurar as estruturas de dados físicas em seu serviço de pesquisa.

O esquema de índice neste exemplo é organizado em torno do conteúdo do hotel. Os dados de exemplo consistem em nomes de vetor e não de vetor e descrições de hotéis fictícios. Esse esquema inclui configurações para indexação de vetor e consultas e para classificação semântica.

  1. No Visual Studio Code, abra o arquivo az-search-vector-quickstart.restcriado anteriormente.

  2. Localize o bloco de código ### Create a new index no arquivo. Este bloco contém a solicitação para criar o índice hotels-vector-quickstart em seu serviço de pesquisa.

    ### Create a new index
    POST  {{baseUrl}}/indexes?api-version=2023-11-01  HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{token}}
    
    {
        "name": "hotels-vector-quickstart",
        "fields": [
            {
                "name": "HotelId", 
                "type": "Edm.String",
                "searchable": false, 
                "filterable": true, 
                "retrievable": true, 
                "sortable": false, 
                "facetable": false,
                "key": true
            },
            {
                "name": "HotelName", 
                "type": "Edm.String",
                "searchable": true, 
                "filterable": false, 
                "retrievable": true, 
                "sortable": true, 
                "facetable": false
            },
            {
                "name": "HotelNameVector",
                "type": "Collection(Edm.Single)",
                "searchable": true,
                "retrievable": true,
                "dimensions": 1536,
                "vectorSearchProfile": "my-vector-profile"
            },
            {
                "name": "Description", 
                "type": "Edm.String",
                "searchable": true, 
                "filterable": false, 
                "retrievable": true, 
                "sortable": false, 
                "facetable": false
            },
            {
                "name": "DescriptionVector",
                "type": "Collection(Edm.Single)",
                "searchable": true,
                "retrievable": true,
                "dimensions": 1536,
                "vectorSearchProfile": "my-vector-profile"
            },
                    {
                "name": "Description_fr", 
                "type": "Edm.String",
                "searchable": true, 
                "filterable": false, 
                "retrievable": true, 
                "sortable": false, 
                "facetable": false,
                "analyzer": "en.microsoft"
            },
            {
                "name": "Description_frvector",
                "type": "Collection(Edm.Single)",
                "searchable": true,
                "retrievable": true,
                "dimensions": 1536,
                "vectorSearchProfile": "my-vector-profile"
            },
            {
                "name": "Category", 
                "type": "Edm.String",
                "searchable": true, 
                "filterable": true, 
                "retrievable": true, 
                "sortable": true, 
                "facetable": true
            },
            {
                "name": "Tags",
                "type": "Collection(Edm.String)",
                "searchable": true,
                "filterable": true,
                "retrievable": true,
                "sortable": false,
                "facetable": true
            },
                    {
                "name": "ParkingIncluded",
                "type": "Edm.Boolean",
                "searchable": false,
                "filterable": true,
                "retrievable": true,
                "sortable": true,
                "facetable": true
            },
            {
                "name": "LastRenovationDate",
                "type": "Edm.DateTimeOffset",
                "searchable": false,
                "filterable": true,
                "retrievable": true,
                "sortable": true,
                "facetable": true
            },
            {
                "name": "Rating",
                "type": "Edm.Double",
                "searchable": false,
                "filterable": true,
                "retrievable": true,
                "sortable": true,
                "facetable": true
            },
            {
                "name": "Address", 
                "type": "Edm.ComplexType",
                "fields": [
                    {
                        "name": "StreetAddress", "type": "Edm.String",
                        "searchable": true, "filterable": false, "retrievable": true, "sortable": false, "facetable": false
                    },
                    {
                        "name": "City", "type": "Edm.String",
                        "searchable": true, "filterable": true, "retrievable": true, "sortable": true, "facetable": true
                    },
                    {
                        "name": "StateProvince", "type": "Edm.String",
                        "searchable": true, "filterable": true, "retrievable": true, "sortable": true, "facetable": true
                    },
                    {
                        "name": "PostalCode", "type": "Edm.String",
                        "searchable": true, "filterable": true, "retrievable": true, "sortable": true, "facetable": true
                    },
                    {
                        "name": "Country", "type": "Edm.String",
                        "searchable": true, "filterable": true, "retrievable": true, "sortable": true, "facetable": true
                    }
                ]
            },
            {
                "name": "Location",
                "type": "Edm.GeographyPoint",
                "searchable": false, 
                "filterable": true, 
                "retrievable": true, 
                "sortable": true, 
                "facetable": false
            }
        ],
        "vectorSearch": {
            "algorithms": [
                {
                    "name": "my-hnsw-vector-config-1",
                    "kind": "hnsw",
                    "hnswParameters": 
                    {
                        "m": 4,
                        "efConstruction": 400,
                        "efSearch": 500,
                        "metric": "cosine"
                    }
                },
                {
                    "name": "my-hnsw-vector-config-2",
                    "kind": "hnsw",
                    "hnswParameters": 
                    {
                        "m": 4,
                        "metric": "euclidean"
                    }
                },
                {
                    "name": "my-eknn-vector-config",
                    "kind": "exhaustiveKnn",
                    "exhaustiveKnnParameters": 
                    {
                        "metric": "cosine"
                    }
                }
            ],
            "profiles": [      
                {
                    "name": "my-vector-profile",
                    "algorithm": "my-hnsw-vector-config-1"
                }
          ]
        },
        "semantic": {
            "configurations": [
                {
                    "name": "my-semantic-config",
                    "prioritizedFields": {
                        "titleField": {
                            "fieldName": "HotelName"
                        },
                        "prioritizedContentFields": [
                            { "fieldName": "Description" }
                        ],
                        "prioritizedKeywordsFields": [
                            { "fieldName": "Category" }
                        ]
                    }
                }
            ]
        }
    }
    
  3. Selecione Enviar solicitação. Você deverá ter uma resposta HTTP/1.1 201 Created.

O corpo da resposta deve incluir a representação JSON do esquema de índice.

{
    "@odata.context": "https://my-demo-search.search.windows.net/$metadata#indexes/$entity",
    "@odata.etag": "\"0x8DD2E70E6C36D8E\"",
    "name": "hotels-vector-quickstart",
    "defaultScoringProfile": null,
    "fields": [
    {
        "name": "HotelId",
        "type": "Edm.String",
        "searchable": false,
        "filterable": true,
        "retrievable": true,
        "sortable": false,
        "facetable": false,
        "key": true,
        "indexAnalyzer": null,
        "searchAnalyzer": null,
        "analyzer": null,
        "dimensions": null,
        "vectorSearchProfile": null,
        "synonymMaps": []
    },
    [MORE FIELD DEFINITIONS OMITTED FOR BREVITY]
    ],
    "scoringProfiles": [],
    "corsOptions": null,
    "suggesters": [],
    "analyzers": [],
    "tokenizers": [],
    "tokenFilters": [],
    "charFilters": [],
    "encryptionKey": null,
    "similarity": {
    "@odata.type": "#Microsoft.Azure.Search.BM25Similarity",
    "k1": null,
    "b": null
    },
    "vectorSearch": {
    "algorithms": [
        {
        "name": "my-hnsw-vector-config-1",
        "kind": "hnsw",
        "hnswParameters": {
            "metric": "cosine",
            "m": 4,
            "efConstruction": 400,
            "efSearch": 500
        },
        "exhaustiveKnnParameters": null
        },
        {
        "name": "my-hnsw-vector-config-2",
        "kind": "hnsw",
        "hnswParameters": {
            "metric": "euclidean",
            "m": 4,
            "efConstruction": 400,
            "efSearch": 500
        },
        "exhaustiveKnnParameters": null
        },
        {
        "name": "my-eknn-vector-config",
        "kind": "exhaustiveKnn",
        "hnswParameters": null,
        "exhaustiveKnnParameters": {
            "metric": "cosine"
        }
        }
    ],
    "profiles": [
        {
        "name": "my-vector-profile",
        "algorithm": "my-hnsw-vector-config-1"
        }
    ]
    },
    "semantic": {
    "defaultConfiguration": null,
    "configurations": [
        {
        "name": "my-semantic-config",
        "prioritizedFields": {
            "titleField": {
            "fieldName": "HotelName"
            },
            "prioritizedContentFields": [
            {
                "fieldName": "Description"
            }
            ],
            "prioritizedKeywordsFields": [
            {
                "fieldName": "Category"
            }
            ]
        }
        }
    ]
    }
}

Principais conclusões sobre a API REST Criar índice:

  • A coleção fields inclui um campo de chave obrigatório e campos de texto e vetor (como Description e DescriptionVector) para busca em vetores e texto. A colocação de campos vetoriais e não vetoriais no mesmo índice permite a realização de consultas híbridas. Por exemplo, você pode combinar filtros, pesquisa de texto com classificação semântica e vetores em uma única operação de consulta.

  • Os campos de vetor devem ser type: Collection(Edm.Single) com dimensions e propriedades vectorSearchProfile .

  • A seção vectorSearch é uma matriz de configurações e perfis do algoritmo do vizinho mais próximo aproximado. Os algoritmos com suporte incluem um mundo pequeno navegável hierárquico e um vizinho k-mais próximo exaustivo. Para obter mais informações, consulte Pontuação de relevância na busca em vetores.

  • A configuração semantic (opcional) permite reclassificar dos resultados da pesquisa. Você pode ranquear resultados em consultas do tipo semantic para os campos de cadeia de caracteres especificados na configuração. Para saber mais, consulte Visão geral da classificação semântica.

Carregar documentos

Criar e carregar o índice são etapas separadas. Você criou o esquema de índice na etapa anterior. Agora você precisa carregar documentos no índice.

Na Pesquisa de IA do Azure, o índice contém todos os dados pesquisáveis e as consultas executadas no serviço de pesquisa. Para chamadas REST, os dados são fornecidos como documentos JSON. Use Documentos - Índice REST API para esta tarefa. O URI é estendido para incluir a coleção docs e a operação index.

  1. No Visual Studio Code, abra o arquivo az-search-vector-quickstart.restcriado anteriormente.

  2. Localize o bloco de código ### Upload documents no arquivo. Este bloco contém a solicitação para carregar documentos no índice hotels-vector-quickstart em seu serviço de pesquisa.

    ### Upload documents
    POST {{baseUrl}}/indexes/hotels-quickstart-vectors/docs/index?api-version=2023-11-01  HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{token}}
    
    {
        "value": [
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "1",
                "HotelName": "Stay-Kay City Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "The hotel is ideally located on the main commercial artery of the city 
                    in the heart of New York.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Boutique",
                "Tags": [
                    "pool",
                    "air conditioning",
                    "concierge"
                ],
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "2",
                "HotelName": "Old Century Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "The hotel is situated in a  nineteenth century plaza, which has been 
                    expanded and renovated to the highest architectural standards to create a modern, 
                    functional and first-class hotel in which art and unique historical elements 
                    coexist with the most modern comforts.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Boutique",
                "Tags": [
                    "pool",
                    "air conditioning",
                    "free wifi",
                    "concierge"
                ]
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "3",
                "HotelName": "Gastronomic Landscape Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "The Hotel stands out for its gastronomic excellence under the management of 
                    William Dough, who advises on and oversees all of the Hotel’s restaurant services.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Resort and Spa",
                "Tags": [
                    "air conditioning",
                    "bar",
                    "continental breakfast"
                ]
            }
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "4",
                "HotelName": "Sublime Palace Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "Sublime Palace Hotel is located in the heart of the historic center of 
                    Sublime in an extremely vibrant and lively area within short walking distance to 
                    the sites and landmarks of the city and is surrounded by the extraordinary beauty 
                    of churches, buildings, shops and monuments. 
                    Sublime Palace is part of a lovingly restored 1800 palace.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Boutique",
                "Tags": [
                    "concierge",
                    "view",
                    "24-hour front desk service"
                ]
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "13",
                "HotelName": "Luxury Lion Resort",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury 
                    accommodations. Moments from the stadium, we feature the best in comfort",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Resort and Spa",
                "Tags": [
                    "view",
                    "free wifi",
                    "pool"
                ]
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "48",
                "HotelName": "Nordick's Valley Motel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "Only 90 miles (about 2 hours) from the nation's capital and nearby 
                    most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring 
                    the caverns?  It's all nearby and we have specially priced packages to help make 
                    our B&B your home base for fun while visiting the valley.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Boutique",
                "Tags": [
                    "continental breakfast",
                    "air conditioning",
                    "free wifi"
                ],
            },
            {
                "@search.action": "mergeOrUpload",
                "HotelId": "49",
                "HotelName": "Swirling Currents Hotel",
                "HotelNameVector": [VECTOR ARRAY OMITTED],
                "Description": 
                    "Spacious rooms, glamorous suites and residences, rooftop pool, walking 
                    access to shopping, dining, entertainment and the city center.",
                "DescriptionVector": [VECTOR ARRAY OMITTED],
                "Category": "Luxury",
                "Tags": [
                    "air conditioning",
                    "laundry service",
                    "24-hour front desk service"
                ]
            }
        ]
    }
    

    Importante

    O código neste exemplo não é executável. Vários caracteres ou linhas foram removidos para fins de brevidade. Use o código em seu arquivo az-search-vector-quickstart.rest para executar a solicitação.

  3. Selecione Enviar solicitação. Você deverá ter uma resposta HTTP/1.1 200 OK. O corpo da resposta deve incluir a representação JSON dos documentos de pesquisa.

Principais conclusões sobre a solicitação Documentos – API REST de Índice:

  • Os documentos na carga consistem em campos definidos no esquema de índice.

  • Os campos de vetor contêm valores de ponto flutuante. O atributo dimensões tem um mínimo de 2 e um máximo de 3.072 valores de ponto flutuante cada. Este início rápido define o atributo dimensões como 1.536 porque esse é o tamanho das inserções geradas pelo modelo text-embedding-ada-002 do OpenAI do Azure.

Executar consultas

Agora que os documentos estão carregados, você pode emitir consultas de vetor em relação a eles usando Documentos - Postagem de Pesquisa (REST).

Nas próximas seções, executaremos consultas no índice hotels-vector-quickstart. As consultas incluem:

As consultas de vetor de exemplo são baseadas em duas cadeias de caracteres:

  • Pesquisar cadeia de caracteres: historic hotel walk to restaurants and shopping
  • Cadeia de caracteres de consulta vetorial (vetorizada em uma representação matemática): classic lodging near running trails, eateries, retail

A cadeia de caracteres de consulta de vetor é semanticamente semelhante à cadeia de caracteres de pesquisa, mas inclui termos que não existem no índice de pesquisa. Se você fizer uma pesquisa por palavra-chave para classic lodging near running trails, eateries, retail, os resultados serão zero. Utilizamos esse exemplo para mostrar como você pode obter resultados relevantes mesmo que não existam termos correspondentes.

  1. No Visual Studio Code, abra o arquivo az-search-vector-quickstart.restcriado anteriormente.

  2. Localize o bloco de código ### Run a single vector query no arquivo. Esse bloco contém a solicitação para consultar o índice de pesquisa.

    ### Run a single vector query
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer {{token}}
    
        {
            "count": true,
            "select": "HotelId, HotelName, Description, Category",
            "vectorQueries": [
                {
                    "vector"": [0.01944167, 0.0040178085
                        . . .  TRIMMED FOR BREVITY
                        010858015, -0.017496133],
                    "k": 7,
                    "fields": "DescriptionVector",
                    "kind": "vector",
                    "exhaustive": true
                }
            ]
        }
    

    Essa consulta de vetor foi encurtada para fins de brevidade. vectorQueries.vector contém o texto vetorizado da entrada da consulta, fields determina quais campos vetoriais são pesquisados e k especifica o número de vizinhos mais próximos a serem retornados.

    A cadeia de caracteres de consulta de vetor é classic lodging near running trails, eateries, retail, que é vetorizada em 1.536 inserções para essa consulta.

    Importante

    O código neste exemplo não é executável. Vários caracteres ou linhas foram removidos para fins de brevidade. Use o código em seu arquivo az-search-vector-quickstart.rest para executar a solicitação.

  3. Selecione Enviar solicitação. Você deverá ter uma resposta HTTP/1.1 200 OK. O corpo da resposta deve incluir a representação JSON dos resultados da pesquisa.

A resposta para o vetor equivalente de classic lodging near running trails, eateries, retail inclui sete resultados. Cada resultado fornece uma pontuação de pesquisa e os campos listados em select. Em uma pesquisa de similaridade, a resposta sempre inclui k resultados ordenados pela pontuação de similaridade do valor.

{
  "@odata.context": "https://my-demo-search.search.windows.net/indexes('hotels-vector-quickstart')/$metadata#docs(*)",
  "@odata.count": 7,
  "value": [
    {
      "@search.score": 0.85773647,
      "HotelId": "48",
      "HotelName": "Nordick's Motel",
      "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.",
      "Category": "Boutique"
    },
    {
      "@search.score": 0.8399132,
      "HotelId": "49",
      "HotelName": "Old Carrabelle Hotel",
      "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center.",
      "Category": "Luxury"
    },
    {
      "@search.score": 0.83839583,
      "HotelId": "13",
      "HotelName": "Historic Lion Resort",
      "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort",
      "Category": "Resort and Spa"
    },
    {
      "@search.score": 0.82543474,
      "HotelId": "4",
      "HotelName": "Sublime Cliff Hotel",
      "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 1800 palace.",
      "Category": "Boutique"
    },
    {
      "@search.score": 0.82380104,
      "HotelId": "1",
      "HotelName": "Secret Point Hotel",
      "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York.",
      "Category": "Boutique"
    },
    {
      "@search.score": 0.8151413,
      "HotelId": "2",
      "HotelName": "Twin Dome Hotel",
      "Description": "The hotel is situated in a  nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts.",
      "Category": "Boutique"
    },
    {
      "@search.score": 0.8133767,
      "HotelId": "3",
      "HotelName": "Triple Landscape Hotel",
      "Description": "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel\u2019s restaurant services.",
      "Category": "Resort and Spa"
    }
  ]
}

Busca em vetores única com filtro

É possível adicionar filtros, mas eles serão aplicados ao conteúdo não vetorial do seu índice. Neste exemplo, o filtro se aplica ao campo Tags para filtrar todos os hotéis que não oferecem Wi-Fi gratuita.

  1. No Visual Studio Code, abra o arquivo az-search-vector-quickstart.restcriado anteriormente.

  2. Localize o bloco de código ### Run a vector query with a filter no arquivo. Esse bloco contém a solicitação para consultar o índice de pesquisa.

    ### Run a vector query with a filter
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer {{token}}
    
        {
            "count": true,
            "select": "HotelId, HotelName, Category, Tags, Description",
            "filter": "Tags/any(tag: tag eq 'free wifi')",
            "vectorFilterMode": "postFilter",
            "vectorQueries": [
            {
                "vector": [ VECTOR OMITTED ],
                "k": 7,
                "fields": "DescriptionVector",
                "kind": "vector",
                "exhaustive": true
            },
        ]
    }
    

    Importante

    O código neste exemplo não é executável. Vários caracteres ou linhas foram removidos para fins de brevidade. Use o código em seu arquivo az-search-vector-quickstart.rest para executar a solicitação.

  3. Selecione Enviar solicitação. Você deverá ter uma resposta HTTP/1.1 200 OK. O corpo da resposta deve incluir a representação JSON dos resultados da pesquisa.

A consulta era a mesma que o exemplo de busca em vetores única anterior, mas inclui um filtro de exclusão pós-processamento e retorna apenas os três hotéis com Wi-Fi gratuito.

{
  "@odata.context": "https://my-demo-search.search.windows.net/indexes('hotels-vector-quickstart')/$metadata#docs(*)",
  "@odata.count": 3,
  "value": [
    {
      "@search.score": 0.85773647,
      "HotelId": "48",
      "HotelName": "Nordick's Motel",
      "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.",
      "Category": "Boutique",
      "Tags": [
        "continental breakfast",
        "air conditioning",
        "free wifi"
      ]
    },
    {
      "@search.score": 0.83839583,
      "HotelId": "13",
      "HotelName": "Historic Lion Resort",
      "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort",
      "Category": "Resort and Spa",
      "Tags": [
        "view",
        "free wifi",
        "pool"
      ]
    },
    {
      "@search.score": 0.8151413,
      "HotelId": "2",
      "HotelName": "Twin Dome Hotel",
      "Description": "The hotel is situated in a  nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts.",
      "Category": "Boutique",
      "Tags": [
        "pool",
        "free wifi",
        "air conditioning",
        "concierge"
      ]
    }
  ]
}

A pesquisa híbrida consiste em consultas de palavra-chave e consultas vetoriais em uma única solicitação de pesquisa. Este exemplo executa simultaneamente a busca em vetores e a busca em texto completo:

  • Pesquisar cadeia de caracteres: historic hotel walk to restaurants and shopping
  • Cadeia de caracteres de consulta vetorial (vetorizada em uma representação matemática): classic lodging near running trails, eateries, retail
  1. No Visual Studio Code, abra o arquivo az-search-vector-quickstart.restcriado anteriormente.

  2. Localize o bloco de código ### Run a hybrid query no arquivo. Esse bloco contém a solicitação para consultar o índice de pesquisa.

    ### Run a hybrid query
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer {{token}}
    
    {
        "count": true,
        "search": "historic hotel walk to restaurants and shopping",
        "select": "HotelName, Description",
        "top": 7,
        "vectorQueries": [
            {
                "vector": [ VECTOR OMITTED],
                "k": 7,
                "fields": "DescriptionVector",
                "kind": "vector",
                "exhaustive": true
            }
        ]
    }
    

    Importante

    O código neste exemplo não é executável. Vários caracteres ou linhas foram removidos para fins de brevidade. Use o código em seu arquivo az-search-vector-quickstart.rest para executar a solicitação.

  3. Selecione Enviar solicitação. Você deverá ter uma resposta HTTP/1.1 200 OK. O corpo da resposta deve incluir a representação JSON dos resultados da pesquisa.

Por ser uma consulta híbrida, os resultados são classificados por Fusão de Reciprocidade de Classificação (RRF). O RRF avalia as pontuações de pesquisa de vários resultados da pesquisa, usa o inverso e mescla e classifica os resultados combinados. O número top de resultados é retornado.

Examine a resposta:

{
    "@odata.count": 7,
    "value": [
        {
            "@search.score": 0.03279569745063782,
            "HotelName": "Luxury Lion Resort",
            "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort"
        },
        {
            "@search.score": 0.03226646035909653,
            "HotelName": "Sublime Palace Hotel",
            "Description": "Sublime Palace Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Palace is part of a lovingly restored 1800 palace."
        },
        {
            "@search.score": 0.03226646035909653,
            "HotelName": "Swirling Currents Hotel",
            "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center."
        },
        {
            "@search.score": 0.03205128386616707,
            "HotelName": "Nordick's Valley Motel",
            "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley."
        },
        {
            "@search.score": 0.03128054738044739,
            "HotelName": "Gastronomic Landscape Hotel",
            "Description": "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services."
        },
        {
            "@search.score": 0.03100961446762085,
            "HotelName": "Old Century Hotel",
            "Description": "The hotel is situated in a  nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts."
        },
        {
            "@search.score": 0.03077651560306549,
            "HotelName": "Stay-Kay City Hotel",
            "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York."
        }
    ]
}

Como o RRF mescla os resultados, ele ajuda a revisar as entradas. Os resultados a seguir são apenas da consulta de texto completo. Os dois principais resultados são Sublime Palace Hotel e History Lion Resort. O Sublime Palace Hotel tem uma pontuação de relevância BM25 mais forte.

{
    "@search.score": 2.2626662,
    "HotelName": "Sublime Palace Hotel",
    "Description": "Sublime Palace Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Palace is part of a lovingly restored 1800 palace."
},
{
    "@search.score": 0.86421645,
    "HotelName": "Luxury Lion Resort",
    "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort"
},

Na consulta somente de vetor, que usa o HNSW para encontrar correspondências, o Sublime Palace Hotel cai para a quarta posição. O Leão Histórico, que ficou em segundo lugar na pesquisa de texto completo e em terceiro na busca em vetores, não experimenta o mesmo alcance de flutuação, então ele aparece como uma das principais correspondências em um conjunto de resultados homogeneizados.

"value": [
    {
        "@search.score": 0.857736,
        "HotelId": "48",
        "HotelName": "Nordick's Valley Motel",
        "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.",
        "Category": "Boutique"
    },
    {
        "@search.score": 0.8399129,
        "HotelId": "49",
        "HotelName": "Swirling Currents Hotel",
        "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center.",
        "Category": "Luxury"
    },
    {
        "@search.score": 0.8383954,
        "HotelId": "13",
        "HotelName": "Luxury Lion Resort",
        "Description": "Unmatched Luxury.  Visit our downtown hotel to indulge in luxury accommodations. Moments from the stadium, we feature the best in comfort",
        "Category": "Resort and Spa"
    },
    {
        "@search.score": 0.8254346,
        "HotelId": "4",
        "HotelName": "Sublime Palace Hotel",
        "Description": "Sublime Palace Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Palace is part of a lovingly restored 1800 palace.",
        "Category": "Boutique"
    },
    {
        "@search.score": 0.82380056,
        "HotelId": "1",
        "HotelName": "Stay-Kay City Hotel",
        "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York.",
        "Category": "Boutique"
    },
    {
        "@search.score": 0.81514084,
        "HotelId": "2",
        "HotelName": "Old Century Hotel",
        "Description": "The hotel is situated in a  nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts.",
        "Category": "Boutique"
    },
    {
        "@search.score": 0.8133763,
        "HotelId": "3",
        "HotelName": "Gastronomic Landscape Hotel",
        "Description": "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services.",
        "Category": "Resort and Spa"
    }
]

Pesquisa híbrida semântica com um filtro

Esta é a última consulta na coleção. Essa consulta híbrida com classificação semântica é filtrada para mostrar somente os hotéis em um raio de 500 quilômetros de Washington D.C. Você pode definir vectorFilterMode como nulo, o que equivale ao padrão (preFilter para índices mais recentes e postFilter para os mais antigos).

  1. No Visual Studio Code, abra o arquivo az-search-vector-quickstart.restcriado anteriormente.

  2. Localize o bloco de código ### Run a hybrid query with semantic reranking no arquivo. Esse bloco contém a solicitação para consultar o índice de pesquisa.

    ### Run a hybrid query with semantic reranking
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        Authorization: Bearer {{token}}
    
    {
        "count": true,
        "search": "historic hotel walk to restaurants and shopping",
        "select": "HotelId, HotelName, Category, Description,Address/City, Address/StateProvince",
        "filter": "geo.distance(Location, geography'POINT(-77.03241 38.90166)') le 500",
        "vectorFilterMode": null,
        "facets": [ "Address/StateProvince"],
        "top": 7,
        "queryType": "semantic",
        "answers": "extractive|count-3",
        "captions": "extractive|highlight-true",
        "semanticConfiguration": "my-semantic-config",
        "vectorQueries": [
            {
                "vector": [ VECTOR OMITTED ],
                "k": 7,
                "fields": "DescriptionVector",
                "kind": "vector",
                "exhaustive": true
            }
        ]
    }
    

    Importante

    O código neste exemplo não é executável. Vários caracteres ou linhas foram removidos para fins de brevidade. Use o código em seu arquivo az-search-vector-quickstart.rest para executar a solicitação.

  3. Selecione Enviar solicitação. Você deverá ter uma resposta HTTP/1.1 200 OK. O corpo da resposta deve incluir a representação JSON dos resultados da pesquisa.

Revise a resposta. A resposta são três hotéis, que são filtrados por localização e facetados por StateProvince e reclassificados semanticamente para promover resultados mais próximos à consulta da cadeia de caracteres da pesquisa (historic hotel walk to restaurants and shopping).

O Swirling Currents Hotel agora ocupa o primeiro lugar. Sem a classificação semântica, o Nordick's Valley Motel é o número um. Com a classificação semântica, os modelos de compreensão de máquina reconhecem que historic se aplica a "hotel, a uma curta distância a pé de restaurantes e lojas."

{
  "@odata.context": "https://my-demo-search.search.windows.net/indexes('hotels-vector-quickstart')/$metadata#docs(*)",
  "@odata.count": 2,
  "@search.facets": {
    "Address/StateProvince": [
      {
        "count": 1,
        "value": "VA"
      }
    ]
  },
  "@search.answers": [],
  "value": [
    {
      "@search.score": 0.03306011110544205,
      "@search.rerankerScore": 2.8773112297058105,
      "HotelId": "49",
      "HotelName": "Old Carrabelle Hotel",
      "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center.",
      "Category": "Luxury",
      "Address": {
        "City": "Arlington",
        "StateProvince": "VA"
      }
    },
    {
      "@search.score": 0.03306011110544205,
      "@search.rerankerScore": 2.1703834533691406,
      "HotelId": "48",
      "HotelName": "Nordick's Motel",
      "Description": "Only 90 miles (about 2 hours) from the nation's capital and nearby most everything the historic valley has to offer.  Hiking? Wine Tasting? Exploring the caverns?  It's all nearby and we have specially priced packages to help make our B&B your home base for fun while visiting the valley.",
      "Category": "Boutique",
      "Address": {
        "City": "Washington D.C.",
        "StateProvince": null
      }
    }
  ]
}

Principais conclusões sobre a API REST Documentos – Search Post:

  • A busca em vetores é especificada por meio da propriedade vectors.value. A pesquisa por palavra-chave é especificada por meio da propriedade search.

  • Em uma pesquisa híbrida, é possível integrar a busca em vetores com a pesquisa de texto completo por palavras-chave. Filtros, verificação ortográfica e classificação semântica se aplicam apenas a conteúdo textual e não a vetores. Nessa consulta final, não existe a semântica answer porque o sistema não produziu uma semântica suficientemente forte.

  • Os resultados reais incluem mais detalhes, inclusive legendas semânticas e destaques. Os resultados foram modificados para facilitar a leitura. Para obter a estrutura completa da resposta, execute a solicitação no cliente REST.

Limpar

Quando você está trabalhando em sua própria assinatura, é uma boa ideia identificar, no final de um projeto, se você ainda precisa dos recursos criados. Recursos deixados em execução podem custar dinheiro. É possível excluir os recursos individualmente ou excluir o grupo de recursos para excluir todo o conjunto de recursos.

Você pode encontrar e gerenciar recursos no portal do Azure usando o link Todos os recursos ou Grupos de recursos no painel de navegação à esquerda.

Se você quiser manter o serviço de pesquisa, mas excluir o índice e os documentos, poderá usar o comando DELETE no cliente REST. Este comando (no final do arquivo az-search-vector-quickstart.rest) exclui o índice hotels-vector-quickstart:

### Delete an index
DELETE  {{baseUrl}}/indexes/hotels-vector-quickstart?api-version=2023-11-01 HTTP/1.1
    Content-Type: application/json
    Authorization: Bearer {{token}}

Próximas etapas

Como próxima etapa, recomendamos aprender a invocar chamadas à API REST sem chaves de API.

Talvez você também queira examinar o código de demonstração para Python, C# ou JavaScript.