Guia de início rápido: pesquisa vetorial usando REST

Saiba como usar as APIs REST de Pesquisa para criar, carregar e consultar vetores no Azure AI Search.

No Azure AI Search, 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 incorporação e configurações em definições de campo vetorial que são usadas em solicitações de consulta. A API Create Index cria o repositório vetorial.

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

Nota

A versão estável da API REST 2023-11-01 depende de soluções externas para fragmentação e incorporação de dados. Se você quiser avaliar os recursos internos de fragmentação e vetorização de dados (visualização pública), tente o assistente Importar e vetorizar dados para obter uma explicação passo a passo de ponta a ponta.

Pré-requisitos

  • Código do Visual Studio com um cliente REST. Se precisar de ajuda para começar, consulte Guia de início rápido: pesquisa de texto usando REST.

  • Azure AI Search, em qualquer região e em qualquer camada. Você pode usar a camada Gratuita para este início rápido, mas Basic ou superior é recomendado para arquivos de dados maiores. Crie ou localize um recurso existente do Azure AI Search em sua assinatura atual.

    A maioria dos serviços existentes suporta pesquisa vetorial. Para um pequeno subconjunto de serviços criados antes de janeiro de 2019, um índice que contém campos vetoriais falha na criação. Nessa situação, um novo serviço deve ser criado.

  • Opcionalmente, para executar o exemplo de consulta que invoca a reclassificação semântica, seu serviço de pesquisa deve ser a camada Básica ou superior, com a classificação semântica habilitada.

  • Opcionalmente, um recurso do Azure OpenAI com uma implantação do text-embedding-ada-002. O arquivo de origem .rest inclui uma etapa opcional para gerar novas incorporações de texto, mas fornecemos incorporações pré-geradas para que você possa omitir essa dependência.

Transferir ficheiros

Baixe um exemplo REST do GitHub para enviar as solicitações neste 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 neste artigo.

Copiar uma chave de serviço de pesquisa e 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. Inicie sessão no portal do Azure. Vá para a página Visão geral e copie o URL. Um ponto final de exemplo poderá ser parecido com https://mydemo.search.windows.net.

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

    Captura de ecrã que mostra o URL e as chaves de API no portal do Azure.

Criar um índice de vetores

Create Index (REST) cria um índice vetorial e configura as estruturas de dados físicas no seu serviço de pesquisa.

O esquema de índice é organizado em torno do conteúdo do hotel. Os dados de amostra consistem em nomes vetoriais e não vetoriais e descrições de sete hotéis fictícios. Esse esquema inclui configurações para indexação vetorial 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 .rest extensão de arquivo.

  4. Cole no exemplo a seguir para criar o hotels-vector-quickstart índice 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 pedido. Lembre-se de que você precisa do cliente REST para enviar solicitações. Você deve ter uma HTTP/1.1 201 Created resposta. O corpo da resposta deve incluir a representação JSON do esquema de índice.

    Pontos principais:

    • A fields coleção inclui um campo de chave obrigatório e campos de texto e vetor (como Description e DescriptionVector) para pesquisa de texto e vetorial. A colocalização de campos vetoriais e não vetoriais no mesmo índice permite 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 vetoriais devem estar type: Collection(Edm.Single) com dimensions e vectorSearchProfile propriedades.
    • A vectorSearch seção é uma matriz de configurações e perfis aproximados de algoritmos vizinhos mais próximos. Os algoritmos suportados incluem mundo pequeno navegável hierárquico e vizinho exaustivo k-mais próximo. Para obter mais informações, consulte Pontuação de relevância na pesquisa vetorial.
    • [Opcional]: A semantic configuração permite a reclassificação dos resultados da pesquisa. Você pode reclassificar os resultados em consultas do tipo semantic para 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. No Azure AI Search, o índice contém todos os dados pesquisáveis e consultas executadas no serviço de pesquisa. Para chamadas REST, os dados são fornecidos como documentos JSON. Use Documents- Index REST API para esta tarefa.

O URI é estendido para incluir a docs coleta e a index operação.

Importante

O exemplo a seguir não é código executável. Para facilitar a leitura, excluímos os valores vetoriais porque cada um contém 1.536 incorporações, o que é muito longo para este artigo. Se você quiser tentar esta etapa, copie o código executável do exemplo 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 útil consistem em campos definidos no esquema de índice.
  • Os campos vetoriais contêm valores de ponto flutuante. O atributo dimensions tem um mínimo de 2 e um máximo de 3.072 valores de ponto flutuante cada. Este guia de início rápido define o atributo dimensions como 1.536 porque esse é o tamanho das incorporações geradas pelo modelo text-embedding-ada-002 da Open AI.

Executar consultas

Agora que os documentos estão carregados, você pode emitir consultas vetoriais contra eles usando Documents - Search Post (REST).

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

As consultas vetoriais nesta seção são baseadas em duas cadeias de caracteres:

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

A cadeia de caracteres de consulta vetorial é semanticamente semelhante à cadeia 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. Usamos este exemplo para mostrar como você pode obter resultados relevantes, mesmo que não haja termos correspondentes.

Importante

Os exemplos a seguir não são código executável. Para facilitar a leitura, excluímos os valores vetoriais porque cada matriz contém 1.536 incorporações, o que é muito longo para este artigo. Se você quiser tentar essas consultas, copie o código executável do exemplo 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 /docs/search operador.

    ### 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
                }
            ]
        }
    

    Esta consulta vetorial é encurtada para brevidade. O vectorQueries.vector contém o texto vetorizado da entrada de 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 vetorial é classic lodging near running trails, eateries, retail, que é vetorizada em 1.536 incorporações para esta consulta.

  2. Veja 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 de 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."
            }
        ]
    }
    

Pesquisa vetorial única com filtro

Você pode adicionar filtros, mas os filtros são aplicados ao conteúdo não vetorial em seu índice. Neste exemplo, o filtro se aplica ao campo para filtrar todos os Tags hotéis que não oferecem Wi-Fi gratuito.

  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. Veja a resposta. A consulta é a mesma do exemplo anterior, mas inclui um filtro de exclusão 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 palavras-chave e consultas vetoriais em uma única solicitação de pesquisa. Este exemplo executa a consulta vetorial e a pesquisa de texto completo simultaneamente:

  • Cadeia de pesquisa: historic hotel walk to restaurants and shopping
  • Seqüência 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
            }
        ]
    }
    

    Como esta é uma consulta híbrida, os resultados são classificados por Reciprocal Rank Fusion (RRF). O RRF avalia as pontuações de pesquisa de vários resultados de pesquisa, faz o inverso e, em seguida, mescla e classifica os resultados combinados. O top número de resultados é retornado.

  2. Veja 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 resultados, ele ajuda a revisar as entradas. Os resultados a seguir são somente da consulta de texto completo. Os dois melhores 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 vetorial, que usa HNSW para encontrar correspondências, o Sublime Cliff Hotel cai para a quarta posição. O Historic Lion, que ficou em segundo lugar na pesquisa de texto completo e terceiro na pesquisa vetorial, não experimenta a mesma faixa de flutuação, por isso aparece como uma correspondência superior em um conjunto de resultados homogeneizado.

        "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

Aqui está a última consulta na coleção. Esta consulta híbrida com classificação semântica é filtrada para mostrar apenas os hotéis dentro de um raio de 500 km de Washington D.C. Você pode definir vectorFilterMode como null, que é equivalente 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. Veja a resposta. A resposta são três hotéis, que são filtrados por localização e facetados e semanticamente reclassificados para StateProvince promover resultados mais próximos da consulta da cadeia de pesquisa (historic hotel walk to restaurants and shopping).

    O Old Carabelle Hotel agora se move para o primeiro lugar. Sem ranking semântico, o Nordick's Hotel é o número um. Com classificação semântica, os modelos de compreensão da máquina reconhecem que historic se aplica a "hotel, a uma curta distância 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 pesquisa vetorial é especificada através da vectors.value propriedade. A pesquisa por palavra-chave é especificada através da search propriedade.
    • Em uma pesquisa híbrida, você pode integrar a pesquisa vetorial com a pesquisa de texto completo sobre palavras-chave. Os filtros, a verificação ortográfica e a classificação semântica aplicam-se apenas ao conteúdo textual e não aos vetores. Nesta consulta final, não há semântica answer porque o sistema não produziu uma que fosse suficientemente forte.
    • Os resultados reais incluem mais detalhes, incluindo legendas semânticas e destaques. Os resultados foram modificados quanto à legibilidade. Para obter a estrutura completa da resposta, execute a solicitação no cliente REST.

Limpeza

Ao trabalhar na sua própria subscrição, recomendamos que verifique, depois de concluir um projeto, se ainda vai precisar dos recursos que criou. Os recursos que deixar em execução podem custar dinheiro. Pode eliminar recursos individualmente ou eliminar o grupo de recursos para eliminar 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 tentar este DELETE comando:

### 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óximos passos

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