Partilhar via


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 pesquisa vetorial para algoritmos que criam o espaço de incorporação e configurações em definições de campo vetorial que são avaliadas no momento da consulta. A API REST 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

Este guia de início rápido omite a etapa de vetorização e fornece incorporações em documentos de exemplo. Se você quiser adicionar fragmentação e vetorização de dados internos sobre seu próprio conteúdo, tente o assistente Importar e vetorizar dados para obter uma explicação passo a passo de ponta a ponta.

Pré-requisitos

Recuperar informações do recurso

As solicitações para o ponto de extremidade de pesquisa devem ser autenticadas e autorizadas. Você pode usar chaves ou funções de API para essa tarefa. Recomendamos o uso de uma conexão sem chave via Microsoft Entra ID.

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

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

  2. Na página inicial Visão geral , localize o URL. Um ponto final de exemplo poderá ser parecido com https://mydemo.search.windows.net.

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

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

    Você obtém o token quando executa o az account get-access-token comando 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 .rest arquivo 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 para este início rápido, ou você pode 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 .rest extensão ou .http arquivo. 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 nesse novo arquivo.

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

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

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

    @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 via ID do Microsoft Entra, você precisa substituir api-key: {{apiKey}} por Authorization: Bearer {{token}} nos cabeçalhos de solicitação. Substitua todas as instâncias que api-key: {{apiKey}} você encontrar no arquivo.

Criar um índice de vetores

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

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

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

  2. Localize o bloco de ### Create a new index código no arquivo. Este bloco contém o pedido para criar o hotels-vector-quickstart índice no 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 pedido. Você deve ter uma HTTP/1.1 201 Created resposta.

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 de criação de índice :

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

  • A configuração (opcional) semantic 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. Você criou o esquema de índice na etapa anterior. Agora você precisa carregar documentos no índice.

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.

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

  2. Localize o bloco de ### Upload documents código no arquivo. Este bloco contém o pedido para carregar documentos para o hotels-vector-quickstart índice no 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 são removidos para maior brevidade. Use o código em seu az-search-vector-quickstart.rest arquivo para executar a solicitação.

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

Principais conclusões sobre o Documents - Index REST API request:

  • 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 do Azure OpenAI.

Executar consultas

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

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

As consultas vetoriais de exemplo 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.

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

  2. Localize o bloco de ### Run a single vector query código no arquivo. Este bloco contém o pedido 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
                }
            ]
        }
    

    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.

    Importante

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

  3. Selecione Enviar pedido. Você deve ter uma HTTP/1.1 200 OK resposta. 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 de 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"
    }
  ]
}

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. No Visual Studio Code, abra o az-search-vector-quickstart.rest arquivo criado anteriormente.

  2. Localize o bloco de ### Run a vector query with a filter código no arquivo. Este bloco contém o pedido 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 são removidos para maior brevidade. Use o código em seu az-search-vector-quickstart.rest arquivo para executar a solicitação.

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

A consulta era a mesma do exemplo anterior de pesquisa de vetor único, 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.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 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. No Visual Studio Code, abra o az-search-vector-quickstart.rest arquivo criado anteriormente.

  2. Localize o bloco de ### Run a hybrid query código no arquivo. Este bloco contém o pedido 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 são removidos para maior brevidade. Use o código em seu az-search-vector-quickstart.rest arquivo para executar a solicitação.

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

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.

Reveja 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 resultados, ele ajuda a revisar as entradas. Os resultados a seguir são somente da consulta de texto completo. Os dois primeiros 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 vetorial, que usa HNSW para encontrar correspondências, o Sublime Palace 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 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

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. No Visual Studio Code, abra o az-search-vector-quickstart.rest arquivo criado anteriormente.

  2. Localize o bloco de ### Run a hybrid query with semantic reranking código no arquivo. Este bloco contém o pedido 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 são removidos para maior brevidade. Use o código em seu az-search-vector-quickstart.rest arquivo para executar a solicitação.

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

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 Swirling Currents Hotel agora se move para o primeiro lugar. Sem ranking semântico, Nordick's Valley Motel é 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.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 Documentos - Search Post REST API:

  • 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 do Azure usando o link Todos os recursos ou Grupos de recursos no painel mais à esquerda.

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

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

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

Você também pode querer rever o código de demonstração para Python, C# ou JavaScript.