Compartir a través de


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 de vectores tiene un esquema de índice que define campos vectoriales y no vectores, una configuración de vector de búsqueda para algoritmos que crean el espacio de inserción y la configuración en las definiciones de campo vectorial que se evalúan en el momento de la consulta. La API de REST Crear índice crea el almacén de vectores.

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

Nota:

En este inicio rápido, se omite el paso de vectorización y se proporcionan incrustaciones en documentos de ejemplo. Si quiere agregar fragmentación y vectorización de datos integrados a través de su propio contenido, pruebe el Asistente para importar y vectorizar datos para ver un tutorial completo.

Requisitos previos

Recuperación de información de recursos

Las solicitudes al punto de conexión de búsqueda deben autenticarse y autorizarse. Puede usar claves de API o roles para esta tarea. Se recomienda usar una conexión sin claves a través de Microsoft Entra ID.

Seleccione la pestaña que se corresponde con su método de autenticación preferido. Use el mismo método para todas las solicitudes de este inicio rápido.

  1. Inicie sesión en Azure Portal y encuentre su servicio de búsqueda.

  2. En la página principal Información general, busque la dirección URL. Un punto de conexión de ejemplo podría ser similar a https://mydemo.search.windows.net.

    Captura de pantalla de la propiedad URL en la página de información general.

  3. Siga los pasos del inicio rápido sin claves para obtener el token de Microsoft Entra.

    Obtendrá el token al ejecutar el comando az account get-access-token en el paso 3 del inicio rápido anterior.

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

Crear o descargar el archivo de código

Use un archivo .rest o .http para ejecutar todas las solicitudes de este inicio rápido. Puede descargar el archivo REST que contiene el código de este inicio rápido, o bien puede crear un nuevo archivo en Visual Studio Code y copiar el código en él.

  1. En Visual Studio Code, cree un nuevo archivo con una extensión de archivo .rest o .http. Por ejemplo, az-search-vector-quickstart.rest. Copie y pegue el contenido sin procesar del archivo Azure-Samples/azure-search-rest-samples/blob/main/Quickstart-vectors/az-search-vector-quickstart.rest en este nuevo archivo.

  2. En la parte superior del archivo, reemplace el valor de marcador de posición de @baseUrl por la dirección URL del servicio de búsqueda. Consulte la sección Recuperar información de recursos para obtener instrucciones sobre cómo encontrar la dirección URL del servicio de búsqueda.

    @baseUrl = PUT-YOUR-SEARCH-SERVICE-URL-HERE
    
  3. En la parte superior del archivo, reemplace el valor del marcador de posición por la autenticación. Consulte la sección Recuperar información de recursos para obtener instrucciones sobre cómo obtener el token de Microsoft Entra o la clave de API.

    Para la autenticación sin clave recomendada mediante Microsoft Entra ID, debe reemplazar @apiKey por la variable @token.

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

    Si prefiere usar una clave de API, reemplace @apiKey por la clave que copió de Azure Portal.

    @apiKey = PUT-YOUR-ADMIN-KEY-HERE
    
  4. Para la autenticación sin clave recomendada mediante Microsoft Entra ID, debe reemplazar api-key: {{apiKey}} por Authorization: Bearer {{token}} en los encabezados de solicitud. Reemplace todas las instancias de api-key: {{apiKey}} que encuentre en el archivo.

Crear un índice vectorial

Use la API de REST Crear índice para crear un índice vectorial y configurar las estructuras de datos físicas en el servicio de búsqueda.

El esquema de índice de este ejemplo se organiza en torno al contenido del hotel. Los datos de ejemplo constan de nombres vectoriales y no vectoriales, así como de descripciones de 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. En Visual Studio Code, abra el archivo az-search-vector-quickstart.rest que creó anteriormente.

  2. Busque el bloque de código ### Create a new index en el archivo. Este bloque contiene la solicitud 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
    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. Seleccione Enviar solicitud. Debe tener una respuesta HTTP/1.1 201 Created.

El cuerpo de la respuesta debe incluir la representación JSON del 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"
            }
            ]
        }
        }
    ]
    }
}

Conclusiones clave sobre la API de REST de Crear índice:

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

  • La configuración (opcional) 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. Ha creado el esquema de índice en el paso anterior. Ahora debe cargar documentos en el índice.

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.

  1. En Visual Studio Code, abra el archivo az-search-vector-quickstart.rest que creó anteriormente.

  2. Busque el bloque de código ### Upload documents en el archivo. Este bloque contiene la solicitud para cargar documentos en el índice hotels-vector-quickstart en el servicio de búsqueda.

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

    El código de este ejemplo no se puede ejecutar. Se quitan varios caracteres o líneas para mayor brevedad. Use el código del archivo az-search-vector-quickstart.rest para ejecutar la solicitud.

  3. Seleccione Enviar solicitud. Debe tener una respuesta HTTP/1.1 200 OK. El cuerpo de la respuesta debe incluir la representación JSON de los documentos de búsqueda.

Conclusiones clave sobre la solicitud de Documentos: índice (API de REST):

  • 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 de dimensiones en 1536, ya que ese es el tamaño de las incrustaciones generadas por el modelo de inserción de texto de Azure OpenAI text-embeding-ada-002.

Ejecutar consultas

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

En las secciones siguientes, ejecutamos consultas en el índice hotels-vector-quickstart. Entre las consultas se incluyen:

Las consultas vectoriales de ejemplo 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.

  1. En Visual Studio Code, abra el archivo az-search-vector-quickstart.rest que creó anteriormente.

  2. Busque el bloque de código ### Run a single vector query en el archivo. Este bloque contiene la solicitud para consultar el índice de búsqueda.

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

    Importante

    El código de este ejemplo no se puede ejecutar. Se quitan varios caracteres o líneas para mayor brevedad. Use el código del archivo az-search-vector-quickstart.rest para ejecutar la solicitud.

  3. Seleccione Enviar solicitud. Debe tener una respuesta HTTP/1.1 200 OK. El cuerpo de la respuesta debe incluir la representación JSON de los resultados de la búsqueda.

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

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. En Visual Studio Code, abra el archivo az-search-vector-quickstart.rest que creó anteriormente.

  2. Busque el bloque de código ### Run a vector query with a filter en el archivo. Este bloque contiene la solicitud 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
        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

    El código de este ejemplo no se puede ejecutar. Se quitan varios caracteres o líneas para mayor brevedad. Use el código del archivo az-search-vector-quickstart.rest para ejecutar la solicitud.

  3. Seleccione Enviar solicitud. Debe tener una respuesta HTTP/1.1 200 OK. El cuerpo de la respuesta debe incluir la representación JSON de los resultados de la búsqueda.

La consulta era la misma que en el anterior ejemplo de búsqueda de vector único, pero incluye un filtro de exclusión posterior al procesamiento y devuelve solo los tres hoteles que tienen Wi-Fi gratis.

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

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. En Visual Studio Code, abra el archivo az-search-vector-quickstart.rest que creó anteriormente.

  2. Busque el bloque de código ### Run a hybrid query en el archivo. Este bloque contiene la solicitud para consultar el índice de búsqueda.

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

    El código de este ejemplo no se puede ejecutar. Se quitan varios caracteres o líneas para mayor brevedad. Use el código del archivo az-search-vector-quickstart.rest para ejecutar la solicitud.

  3. Seleccione Enviar solicitud. Debe tener una respuesta HTTP/1.1 200 OK. El cuerpo de la respuesta debe incluir la representación JSON de los resultados de la búsqueda.

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.

Revise la respuesta:

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

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 Palace Hotel e History Lion Resort. El Sublime Palace Hotel tiene una puntuación de relevancia BM25 más fuerte.

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

En la consulta de solo vector, que usa HNSW para buscar coincidencias, el Sublime Palace 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 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"
    }
]

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. En Visual Studio Code, abra el archivo az-search-vector-quickstart.rest que creó anteriormente.

  2. Busque el bloque de código ### Run a hybrid query with semantic reranking en el archivo. Este bloque contiene la solicitud para consultar el índice de búsqueda.

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

    El código de este ejemplo no se puede ejecutar. Se quitan varios caracteres o líneas para mayor brevedad. Use el código del archivo az-search-vector-quickstart.rest para ejecutar la solicitud.

  3. Seleccione Enviar solicitud. Debe tener una respuesta HTTP/1.1 200 OK. El cuerpo de la respuesta debe incluir la representación JSON de los resultados de la búsqueda.

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

El Swirling Currents Hotel ahora se encuentra en el lugar superior. Sin clasificación semántica, el Valley Motel de Nordick 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.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
      }
    }
  ]
}

Conclusiones clave sobre la API de REST de Documentos: búsqueda de POST:

  • 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 bien eliminar el grupo de recursos para eliminar todo el conjunto de recursos.

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

Si desea mantener el servicio de búsqueda, pero quiere eliminar el índice y los documentos, puede usar el comando DELETE en el cliente de REST. Este comando (al final del archivo az-search-vector-quickstart.rest) elimina el índice hotels-vector-quickstart:

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

Pasos siguientes

Como paso siguiente, se recomienda aprender a invocar llamadas a la API de REST sin claves de API.

Quizás también quiera revisar el código de demostración para Python, C# o JavaScript.