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 vetor para algoritmos que criam o espaço de inserção e configurações em definições de campo de vetor que são usadas em solicitações de consulta. A API 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

A versão estável da API REST 2023-11-01 depende de soluções externas para agrupamento e inserção de dados. Se você quiser avaliar os recursos de fragmentação de dados e vetorização internos (visualização pública), experimente o assistente Importar e vetorizar dados para um tutorial completo.

Pré-requisitos

Baixar arquivos

Baixe uma amostra REST do GitHub para enviar as solicitações nesse início rápido. Para obter mais informações, consulte Baixando arquivos do GitHub.

Você também pode iniciar um novo arquivo em seu sistema local e criar solicitações manualmente usando as instruções nesse artigo.

Copiar uma chave de serviço de pesquisa e uma URL

As chamadas REST exigem o ponto de extremidade do serviço de pesquisa e uma chave de API em cada solicitação. Você pode obter esses valores no portal do Azure.

  1. Entre no portal do Azure. Vá para a página Visão Geral e copie a URL. Um ponto de extremidade de exemplo pode parecer com https://mydemo.search.windows.net.

  2. Selecione Configurações>Chaves e copie uma chave de administração. As chaves de administrador são usadas para adicionar, modificar e excluir objetos. Há duas chaves de administrador intercambiáveis. Copie uma delas.

    Captura de tela mostrado a URL e as chaves de API no portal do Microsoft Azure.

Criar um índice de vetor

Criar índice (REST) cria um índice de vetor e configura as estruturas de dados físicas em seu serviço de pesquisa.

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

  1. Abra um novo arquivo de texto no Visual Studio Code.

  2. Defina variáveis para o ponto de extremidade de pesquisa e a chave de API que você coletou anteriormente.

    @baseUrl = PUT-YOUR-SEARCH-SERVICE-URL-HERE
    @apiKey = PUT-YOUR-ADMIN-API-KEY-HERE
    
  3. Salve o arquivo com uma extensão de arquivo .rest.

  4. Cole o exemplo a seguir 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
        api-key: {{apiKey}}
    
    {
        "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": "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": "Address", 
                "type": "Edm.ComplexType",
                "fields": [
                    {
                        "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": "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": "Tags" }
                        ]
                    }
                }
            ]
        }
    }
    
  5. Selecione Enviar solicitação. Lembre-se de que você precisa do cliente REST para enviar solicitações. Você deverá ter uma resposta HTTP/1.1 201 Created. O corpo da resposta deve incluir a representação JSON do esquema de índice.

    Pontos principais:

    • 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.
    • [Opcional]: a configuração semantic habilita o reordenamento 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. 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.

Importante

O exemplo a seguir não é um código executável. Para facilitar a leitura, excluímos os valores de vetor porque cada um contém 1.536 inserções, o que é muito longo para este artigo. Se você quiser experimentar esta etapa, copie o código executável da amostra no GitHub.

### Upload documents
POST {{baseUrl}}/indexes/hotels-quickstart-vectors/docs/index?api-version=2023-11-01  HTTP/1.1
Content-Type: application/json
api-key: {{apiKey}}

{
    "value": [
        {
            "@search.action": "mergeOrUpload",
            "HotelId": "1",
            "HotelName": "Secret Point Motel",
            "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": "Twin Dome 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": "Triple 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 Cliff Hotel",
            "HotelNameVector": [VECTOR ARRAY OMITTED],
            "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.",
            "DescriptionVector": [VECTOR ARRAY OMITTED],
            "Category": "Boutique",
            "Tags": [
                "concierge",
                "view",
                "24-hour front desk service"
            ]
        },
        {
            "@search.action": "mergeOrUpload",
            "HotelId": "13",
            "HotelName": "Historic 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": "Nordicks Hotel",
            "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": "Old Carrabelle 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"
            ]
        }
    ]
}

Pontos principais:

  • 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 da Open AI.

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).

Há várias consultas para demonstrar vários padrões:

As consultas de vetor nesta seção 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.

Importante

Os exemplos a seguir não são código executável. Para facilitar a leitura, excluímos os valores de vetor porque cada matriz contém 1.536 inserções, o que é muito longo para este artigo. Se você quiser experimentar essas consultas, copie o código executável da amostra no GitHub.

  1. Cole em uma solicitação POST para consultar o índice de pesquisa. Em seguida, selecione Enviar solicitação. O URI é estendido para incluir o operador /docs/search.

    ### Run a query
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        api-key: {{apiKey}}
    
        {
            "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.

  2. Revise a resposta. 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.857736,
                "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."
            },
            {
                "@search.score": 0.8399129,
                "HotelName": "Old Carrabelle Hotel",
                "Description": "Spacious rooms, glamorous suites and residences, rooftop pool, walking access to shopping, dining, entertainment and the city center."
            },
            {
                "@search.score": 0.8383954,
                "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"
            },
            {
                "@search.score": 0.8254346,
                "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."
            },
            {
                "@search.score": 0.82380056,
                "HotelName": "Secret Point Hotel",
                "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York."
            },
            {
                "@search.score": 0.81514084,
                "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."
            },
            {
                "@search.score": 0.8133763,
                "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’s restaurant services."
            }
        ]
    }
    

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. Cole em uma solicitação POST 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
        api-key: {{apiKey}}
    
        {
            "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
            },
        ]
    }
    
  2. Revise a resposta. A consulta é a mesma do exemplo anterior, mas inclui um filtro de exclusão de pós-processamento e retorna apenas os três hotéis que têm Wi-Fi gratuito.

    {
    
        "@odata.count": 3,
        "value": [
            {
                "@search.score": 0.857736,
                "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.",
                "Tags": [
                    "continental breakfast",
                    "air conditioning",
                    "free wifi"
                ]
            },
            {
                "@search.score": 0.8383954,
                "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",
                "Tags": [
                    "view",
                    "free wifi",
                    "pool"
                ]
            },
            {
                "@search.score": 0.81514084,
                "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.",
                "Tags": [
                    "pool",
                    "free wifi",
                    "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. Cole em uma solicitação POST para consultar o índice de pesquisa. Em seguida, selecione Enviar solicitação.

    ### Run a hybrid query
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        api-key: {{apiKey}}
    
    {
        "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
            }
        ]
    }
    

    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.

  2. Revise a resposta.

    {
        "@odata.count": 7,
        "value": [
            {
                "@search.score": 0.03279569745063782,
                "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"
            },
            {
                "@search.score": 0.03226646035909653,
                "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."
            },
            {
                "@search.score": 0.03226646035909653,
                "HotelName": "Old Carrabelle 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 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": "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’s restaurant services."
            },
            {
                "@search.score": 0.03100961446762085,
                "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."
            },
            {
                "@search.score": 0.03077651560306549,
                "HotelName": "Secret Point 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 Cliff Hotel e History Lion Resort. O Sublime Cliff Hotel tem uma pontuação de relevância BM25 mais forte.

            {
                "@search.score": 2.2626662,
                "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."
            },
            {
                "@search.score": 0.86421645,
                "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"
                },
    

    Na consulta somente de vetor, que usa o HNSW para encontrar correspondências, o Sublime Cliff Hotel cai para a quarta posição. O History Lion, 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 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": "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.8383954,
                "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.8254346,
                "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.82380056,
                "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.81514084,
                "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.8133763,
                "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’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. Cole em uma solicitação POST para consultar o índice de pesquisa. Em seguida, selecione Enviar solicitação.

    ### Run a hybrid query
    POST {{baseUrl}}/indexes/hotels-vector-quickstart/docs/search?api-version=2023-11-01  HTTP/1.1
        Content-Type: application/json
        api-key: {{apiKey}}
    
    {
        "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
            }
        ]
    }
    
  2. 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 Old Carabelle Hotel agora ocupa o primeiro lugar. Sem a classificação semântica, o Nordick's Hotel é 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.count": 3,
        "@search.facets": {
            "Address/StateProvince": [
                {
                    "count": 1,
                    "value": "NY"
                },
                {
                    "count": 1,
                    "value": "VA"
                }
            ]
        },
        "@search.answers": [],
        "value": [
            {
                "@search.score": 0.03306011110544205,
                "@search.rerankerScore": 2.5094974040985107,
                "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.0370211601257324,
                "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
                }
            },
            {
                "@search.score": 0.032258063554763794,
                "@search.rerankerScore": 1.6706111431121826,
                "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",
                "Address": {
                    "City": "New York",
                    "StateProvince": "NY"
                }
            }
        ]
    }
    

    Pontos principais:

    • 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. Você pode excluir os recursos individualmente ou excluir o grupo de recursos para excluir todo o conjunto de recursos.

Você pode localizar e gerenciar recursos no portal usando o link Todos os recursos ou Grupos de recursos no painel mais à esquerda.

Você também pode experimentar este comando DELETE:

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

Próximas etapas

Como próxima etapa, recomendamos que você analise o código de demonstração para Python, C# ou JavaScript.