Inicio rápido: vector de búsqueda mediante REST

Descubra cómo usar las API REST de Búsqueda para crear, cargar y consultar vectores en Búsqueda de Azure AI.

En la Búsqueda de Azure AI, un almacén vectorial tiene un esquema de índice que define los campos vectoriales y no vectoriales, una configuración vectorial para los algoritmos que crean el espacio de inserción y una configuración sobre las definiciones de los campos vectoriales que se usan en las solicitudes de consulta. La API Crear índice crea el almacén de vectores.

Si no tiene una suscripción a Azure, cree una cuenta gratuita antes de empezar.

Nota:

La versión 2023-11-01 estable de la API REST depende de las soluciones externas para la fragmentación y la inserción de datos. Si quiere evaluar las características integradas de fragmentación y vectorización de datos (versión preliminar pública), pruebe el Asistente para importar y vectorizar datos para ver un tutorial completo.

Requisitos previos

  • Visual Studio Code con un cliente REST. Si necesita ayuda para empezar, vea Inicio rápido: Búsqueda de texto mediante REST.

  • Búsqueda de Azure AI, en cualquier región y en cualquier nivel. Puede usar el nivel Gratis para este inicio rápido, pero se recomienda Básico o superior para archivos de datos más grandes. Cree un servicio de Búsqueda de Azure AI o busque uno existente en su suscripción actual.

    La mayoría de los servicios existentes admiten el vector de búsqueda. En el caso de un pequeño subconjunto de servicios creados antes de enero de 2019, se producirá un error al crear un índice que contiene campos de vector. En esta situación, se debe crear un nuevo servicio.

  • Opcionalmente, para ejecutar la consulta de ejemplo que invoca la reclasificación semántica, el servicio de búsqueda debe ser de nivel Básico, o superior, y debe tener la clasificación semántica habilitada.

  • Opcionalmente, un recurso de Azure OpenAI con una implementación de text-embedding-ada-002. El archivo .rest de origen incluye un paso opcional para generar nuevas incrustaciones de texto, pero proporcionamos inserciones generadas previamente para que pueda omitir esta dependencia.

Descarga de archivos

Descargue un ejemplo de REST de GitHub para enviar las solicitudes de este inicio rápido. Para obtener más información, consulte Descarga de archivos de GitHub.

También puede iniciar un nuevo archivo en el sistema local y crear solicitudes manualmente con las instrucciones de este artículo.

Copiar una clave y una dirección URL del servicio de búsqueda

Las llamadas de REST requieren el punto de conexión de servicio de búsqueda y una clave de API en cada solicitud. Puede obtener estos valores en Azure Portal.

  1. Inicie sesión en Azure Portal. Vaya a la página de información general y copie la dirección URL. Un punto de conexión de ejemplo podría ser similar a https://mydemo.search.windows.net.

  2. Seleccione Configuración>Claves y copie una clave de administrador. Las claves de administrador se utilizan para agregar, modificar y eliminar objetos. Hay dos claves de administrador intercambiables. Copie una de las dos.

    Captura de pantalla que muestra la dirección URL y las claves de API en Azure Portal.

Crear un índice vectorial

Crear índice (REST) crea un índice vectorial y configura las estructuras de datos físicas en el servicio de búsqueda.

El esquema de índice se organiza en torno al contenido del hotel. Los datos de ejemplo constan de nombres vectoriales y no vectoriales, así como de descripciones de siete hoteles ficticios. En este esquema se incluyen configuraciones para la indexación de vectores y las consultas, así como para la clasificación semántica.

  1. Abra un nuevo archivo de texto en Visual Studio Code.

  2. Establezca variables en el punto de conexión de búsqueda y la clave de API que recopiló anteriormente.

    @baseUrl = PUT-YOUR-SEARCH-SERVICE-URL-HERE
    @apiKey = PUT-YOUR-ADMIN-API-KEY-HERE
    
  3. Guarde el archivo con una extensión de archivo .rest.

  4. Pegue el siguiente ejemplo para crear el índice hotels-vector-quickstart en el servicio de búsqueda.

    ### 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. Seleccione Enviar solicitud. Recuerde que necesita el cliente REST para enviar solicitudes. Debe tener una respuesta HTTP/1.1 201 Created. El cuerpo de la respuesta debe incluir la representación JSON del esquema de índice.

    Puntos clave:

    • La colección fields incluye un campo de clave obligatorio y campos de texto y vector (como Description y DescriptionVector) para la el texto y el vector de búsqueda. La colocación de campos de vectoriales y no vectoriales en el mismo índice permite consultas híbridas. Por ejemplo, puede combinar filtros, búsqueda de texto con clasificación semántica y vectores en una sola operación de consulta.
    • Los campos de vector deben tener propiedades type: Collection(Edm.Single), dimensions y vectorSearchProfile.
    • La sección vectorSearch es una matriz de configuraciones y perfiles de algoritmos vecinos más próximos aproximados. Los algoritmos compatibles incluyen un mundo pequeño navegable jerárquico y el vecinos más próximo k exhaustivo. Para más información, consulte Relevancia y puntuación en el vector de búsqueda.
    • [Opcional]: La configuración de semantic permite reordenar los resultados de búsqueda. Puede volver a generar resultados en consultas de tipo semantic para los campos de cadena que se especifican en la configuración. Para saber más información, consulte Introducción a la clasificación semántica.

Cargar documentos

La creación y la carga del índice son pasos independientes. En Búsqueda de Azure AI, el índice contiene todos los datos que se pueden buscar y las consultas se ejecutan en el servicio de búsqueda. En las llamadas de REST, los datos se proporcionan como documentos JSON. Use Documentación: Index REST API para esta tarea.

El URI se amplía para que incluya la colección docs y la operación index.

Importante

El ejemplo siguiente no es código ejecutable. Para mejorar la legibilidad, hemos excluido los valores vectoriales porque cada uno contiene 1 536 inserciones, lo cual es demasiado largo para este artículo. Si quiere probar este paso, copie el código ejecutable del ejemplo en 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"
            ]
        }
    ]
}

Puntos clave:

  • Los documentos de la carga constan de campos definidos en el esquema de índice.
  • Los campos vectoriales contienen valores de punto flotante. El atributo dimensiones tiene un mínimo de 2 y un máximo de 3 072 valores en número de punto flotante cada uno. En este inicio rápido se establece el atributo dimensiones en 1 536 porque ese es el tamaño de las inserciones generadas por el modelo de text-embedding-ada-002 de Open AI.

Ejecutar consultas

Ahora que se han cargado los documentos, puede emitir consultas vectoriales en ellos mediante Documentación: Search Post (REST).

Hay varias consultas para mostrar los diversos patrones:

Las consultas vectoriales de esta sección se basan en dos cadenas:

  • Buscar cadena: historic hotel walk to restaurants and shopping
  • Cadena de consulta vector (vectorizado en una representación matemática): classic lodging near running trails, eateries, retail

La cadena de consulta vectorial es semánticamente similar a la cadena de búsqueda, pero incluye términos que no existen en el índice de búsqueda. Si realiza una búsqueda de palabra clave para classic lodging near running trails, eateries, retail, los resultados son cero. Usamos este ejemplo para mostrar cómo puede obtener resultados relevantes incluso si no hay términos coincidentes.

Importante

Los ejemplos siguientes no son código ejecutable. Para mejorar la legibilidad, hemos excluido los valores vectoriales porque cada matriz contiene 1 536 inserciones, lo cual es demasiado largo para este artículo. Si quiere probar estas consultas, copie el código ejecutable del ejemplo en GitHub.

  1. Pegue una solicitud POST para consultar el índice de búsqueda. Luego, seleccione Enviar solicitud. El URI se amplía para que incluya el 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
                }
            ]
        }
    

    Esta consulta vectorial se abrevia para mayor brevedad. vectorQueries.vector contiene el texto vectorizado de la entrada de consulta, fields determina qué campos vectoriales se buscan y k especifica el número de vecinos más próximos que se van a devolver.

    La cadena de consulta vectorial es classic lodging near running trails, eateries, retail, que se vectoriza en 1 536 incrustaciones para esta consulta.

  2. Revise la respuesta. La respuesta del vector equivalente a classic lodging near running trails, eateries, retail incluye siete resultados. Cada resultado proporciona una puntuación de búsqueda y los campos enumerados en select. En una búsqueda de similitud, la respuesta siempre incluirá los k resultados ordenados por la puntuación de similitud de valores.

    {
        "@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."
            }
        ]
    }
    

Vector de búsqueda único con filtro

Puede agregar filtros, pero los filtros se aplican al contenido no vectorial del índice. En este ejemplo, el filtro se aplica al campo Tags, para filtrar los hoteles que no proporcionan Wi-Fi gratis.

  1. Pegue una solicitud POST para consultar el índice de búsqueda.

    ### 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 la respuesta. La consulta es la misma que en el ejemplo anterior, pero incluye un filtro de exclusión posterior al procesamiento y devuelve solo los tres hoteles que tienen Wi-Fi gratis.

    {
    
        "@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"
                ]
            }
        ]
    }
    

La búsqueda híbrida consta de consultas de palabras clave y consultas vectoriales en una única solicitud de búsqueda. En este ejemplo se ejecuta la consulta vectorial y la búsqueda de texto completo simultáneamente:

  • Buscar cadena: historic hotel walk to restaurants and shopping
  • Cadena de consulta vector (vectorizado en una representación matemática): classic lodging near running trails, eateries, retail
  1. Pegue una solicitud POST para consultar el índice de búsqueda. Luego, seleccione Enviar solicitud.

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

    Dado que se trata de una consulta híbrida, los resultados se clasifican por la fusión de clasificación recíproca (RRF). RRF evalúa las puntuaciones de búsqueda de varios resultados de búsqueda, toma el inverso y, después, combina y ordena los resultados combinados. Se devuelve el número de resultados top.

  2. Revise la respuesta.

    {
        "@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."
            }
        ]
    }
    

    Dado que RRF combina los resultados, ayuda a revisar las entradas. Los siguientes resultados proceden solo de la consulta de texto completo. Los dos mejores resultados son Sublime Cliff Hotel e History Lion Resort. El Sublime Cliff Hotel tiene una puntuación de relevancia BM25 más fuerte.

            {
                "@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"
                },
    

    En la consulta de solo vector que usa HNSW para buscar coincidencias, Sublime Cliff Hotel cae a la cuarta posición. Historic Lion, que fue el segundo en la búsqueda de texto completo y el tercero en vector de búsqueda, no experimenta el mismo intervalo de fluctuaciones, así que aparece como una coincidencia superior en un 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"
            }
        ]
    

Búsqueda híbrida semántica con un filtro

Esta es la última consulta de la colección. Esta consulta híbrida con clasificación semántica se filtra para mostrar solo los hoteles dentro de un radio de 500 kilómetros de Washington D.C. Puede establecer vectorFilterMode en null, que es equivalente al valor predeterminado (preFilter para índices más recientes y postFilter para los más antiguos).

  1. Pegue una solicitud POST para consultar el índice de búsqueda. Luego, seleccione Enviar solicitud.

    ### 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 la respuesta. La respuesta es tres hoteles, que se filtran por ubicación y por facetas por StateProvince y se vuelven a clasificar semánticamente para promover resultados más cercanos a la consulta de cadena de búsqueda (historic hotel walk to restaurants and shopping).

    Old Carabelle Hotel ahora se encuentra en el lugar más alto. Sin clasificación semántica, el Nordick's es el número uno. Con la clasificación semántica, los modelos de comprensión de la máquina reconocen que historic se aplica al "hotel", a poca distancia a pie de los restaurantes (para cenar) y las compras".

    {
        "@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"
                }
            }
        ]
    }
    

    Puntos clave:

    • El vector de búsqueda se especifica mediante la propiedad vectors.value. La búsqueda de palabra clave se especifica mediante la propiedad search.
    • En una búsqueda híbrida, puede integrar el vector de búsqueda con búsqueda de texto completo sobre palabras clave. Los filtros, la revisión ortográfica y la clasificación semántica solo se aplican al contenido textual y no a los vectores. En esta consulta final, no hay ninguna answer semántica porque el sistema no ha producido una suficientemente fuerte.
    • Entre los resultados reales se incluyen más detalles, incluidos los títulos semánticos y los resaltados. Los resultados se modificaron para mejorar la legibilidad. Para obtener la estructura completa de la respuesta, ejecute la solicitud en el cliente REST.

Limpieza

Cuando trabaje con su propia suscripción, es una buena idea al final de un proyecto identificar si todavía se necesitan los recursos que ha creado. Los recursos que se dejan en ejecución pueden costarle mucho dinero. Puede eliminar los recursos de forma individual o eliminar el grupo de recursos para eliminar todo el conjunto de recursos.

Puede encontrar y administrar recursos en el portal mediante el vínculo Todos los recursos o Grupos de recursos en el panel izquierdo.

También puede probar 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}}

Pasos siguientes

Como siguiente paso, recomendamos que revise el código de demostración para Python, C# o JavaScript.