Краткое руководство. Поиск вектора с помощью REST

Узнайте, как использовать ИНТЕРФЕЙСы REST API поиска для создания, загрузки и запроса в службе поиска ИИ Azure.

В службе "Поиск ИИ Azure" векторное хранилище содержит схему индекса, которая определяет поля векторов и невекторов, векторную конфигурацию для алгоритмов, создающих пространство внедрения, и параметры определений векторных полей, используемых в запросах. API создания индекса создает векторное хранилище.

Если у вас нет подписки Azure, создайте бесплатную учетную запись, прежде чем приступить к работе.

Примечание.

Стабильная версия REST API 2023-11-01 зависит от внешних решений для фрагментирования и внедрения данных. Если вы хотите оценить встроенные функции блока данных и векторизации (общедоступная предварительная версия), попробуйте мастер импорта и векторизации данных для сквозного пошагового руководства.

Необходимые компоненты

  • Visual Studio Code с клиентом REST. Если вам нужна помощь по началу работы, см . краткое руководство. Поиск текста с помощью REST.

  • Поиск ИИ Azure в любом регионе и на любом уровне. Вы можете использовать уровень "Бесплатный" для этого краткого руководства, но для больших файлов данных рекомендуется использовать базовый или более высокий уровень. Создайте или найдите существующий ресурс поиска ИИ Azure в текущей подписке.

    Большинство существующих служб поддерживают векторный поиск. Для небольшого подмножества служб, созданных до января 2019 года, индекс, содержащий поля векторов, завершается сбоем при создании. В этой ситуации необходимо создать новую службу.

  • При необходимости для запуска примера запроса, вызывающего семантические повторения, служба поиска должна быть базовой или более поздней, с поддержкой семантического ранжирования.

  • При необходимости ресурс Azure OpenAI с развертываниемtext-embedding-ada-002. Исходный .rest файл включает необязательный шаг для создания новых вставок текста, но мы предоставляем предварительно созданные внедрения, чтобы можно было опустить эту зависимость.

Загрузка файлов

Скачайте пример REST из GitHub, чтобы отправить запросы в этом кратком руководстве. Дополнительные сведения см. в статье "Скачивание файлов с GitHub".

Вы также можете запустить новый файл в локальной системе и вручную создать запросы, выполнив инструкции в этой статье.

Копирование ключа службы поиска и URL-адреса

Вызовы REST требуют конечной точки службы поиска и ключа API для каждого запроса. Эти значения можно получить из портал Azure.

  1. Войдите на портал Azure. Перейдите на страницу обзора и скопируйте URL-адрес. Пример конечной точки может выглядеть так: https://mydemo.search.windows.net.

  2. Выберите Параметры> Keys и скопируйте ключ администратора. Администратор ключи используются для добавления, изменения и удаления объектов. Существует два взаимозаменяемых ключа администратора. Скопируйте любой из них.

    Снимок экрана: url-адрес и ключи API в портал Azure.

Создание векторного индекса

Создание индекса (REST) создает векторный индекс и настраивает структуры физических данных в службе поиска.

Схема индекса организована вокруг содержимого отеля. Пример данных состоит из векторных и невекторных имен и описаний семи вымышленных отелей. Эта схема включает конфигурации для индексирования векторов и запросов, а также для семантического ранжирования.

  1. Откройте новый текстовый файл в Visual Studio Code.

  2. Задайте переменные в конечную точку поиска и ключ API, собранный ранее.

    @baseUrl = PUT-YOUR-SEARCH-SERVICE-URL-HERE
    @apiKey = PUT-YOUR-ADMIN-API-KEY-HERE
    
  3. Сохраните файл с расширением .rest файла.

  4. Вставьте следующий пример, чтобы создать hotels-vector-quickstart индекс в службе поиска.

    ### 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. Щелкните Отправить запрос. Помните, что для отправки запросов требуется клиент REST. У вас должен быть HTTP/1.1 201 Created ответ. Текст ответа должен содержать представление JSON схемы индекса.

    Основные моменты:

    • Коллекция fields содержит обязательные ключевые поля и текстовые и векторные поля (например Description , и DescriptionVector) для поиска текста и вектора. Совместное размещение полей вектора и невектора в том же индексе позволяет выполнять гибридные запросы. Например, можно объединить фильтры, текстовый поиск с семантическим ранжированием и векторы в одну операцию запроса.
    • Поля векторов должны быть type: Collection(Edm.Single) со свойствами dimensions и vectorSearchProfile свойствами.
    • Этот vectorSearch раздел представляет собой массив приблизительных конфигураций и профилей ближайших соседних алгоритмов. Поддерживаемые алгоритмы включают иерархический навигацию по небольшому миру и исчерпывающий k-ближайший сосед. Дополнительные сведения см. в разделе оценки релевантности в векторном поиске.
    • [Необязательно]: semantic конфигурация позволяет повторно использовать результаты поиска. Вы можете повторно выполнять запросы типа semantic для строковых полей, указанных в конфигурации. Дополнительные сведения см. в обзоре семантического ранжирования.

Отправить документы

Создание и загрузка индекса являются отдельными шагами. В службе поиска ИИ Azure индекс содержит все данные, доступные для поиска, и запросы, выполняемые в службе поиска. Для вызовов REST данные предоставляются в виде документов JSON. Используйте REST API индексов для этой задачи.

Универсальный код ресурса (URI) расширен для включения docs коллекции и index операции.

Внимание

В следующем примере не выполняется код. Для удобства чтения мы исключили векторные значения, так как каждая из них содержит 1536 внедрения, что слишком долго для этой статьи. Если вы хотите попробовать этот шаг, скопируйте выполняемый код из примера на 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"
            ]
        }
    ]
}

Основные моменты:

  • Документы в полезных данных состоят из полей, определенных в схеме индекса.
  • Векторные поля содержат значения с плавающей запятой. Атрибут измерений имеет не менее 2 и не более 3072 значений с плавающей запятой. В этом кратком руководстве атрибут измерений присваивается значение 1536, так как это размер внедрения, создаваемых моделью Open AI , встраивающей текст ada-002 .

Выполнение запросов

Теперь, когда документы загружены, вы можете выдавать векторные запросы к ним с помощью документов — post (REST).

Существует несколько запросов для демонстрации различных шаблонов:

Векторные запросы в этом разделе основаны на двух строках:

  • Строка поиска: historic hotel walk to restaurants and shopping
  • Строка векторного запроса (векторизованная в математическое представление): classic lodging near running trails, eateries, retail

Строка векторного запроса семантически похожа на строку поиска, но она содержит термины, которые не существуют в индексе поиска. Если вы выполняете поиск ключевое словоclassic lodging near running trails, eateries, retail, результаты равны нулю. В этом примере показано, как можно получить соответствующие результаты, даже если нет подходящих условий.

Внимание

В следующих примерах не выполняется код. Для удобства чтения мы исключили векторные значения, так как каждый массив содержит 1536 внедрения, что слишком долго для этой статьи. Если вы хотите попробовать эти запросы, скопируйте выполняемый код из примера на GitHub.

  1. Вставьте запрос POST для запроса индекса поиска. Затем нажмите кнопку "Отправить запрос". Универсальный код ресурса (URI) расширен для включения /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
                }
            ]
        }
    

    Этот векторный запрос сокращен для краткости. Содержит vectorQueries.vector векторный текст входных данных запроса, fields определяет, какие поля векторов выполняются поиск, а k также указывает число ближайших соседей, возвращаемых.

    Строка векторного запроса , classic lodging near running trails, eateries, retailкоторая векторизирована в 1536 внедрения для этого запроса.

  2. Проверьте ответ. Ответ для векторного эквивалента classic lodging near running trails, eateries, retail включает семь результатов. Каждый результат предоставляет оценку поиска и поля, перечисленные в select. В поиске сходства ответ всегда содержит k результаты, упорядоченные по оценке сходства значений.

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

Поиск одного вектора с фильтром

Вы можете добавить фильтры, но фильтры применяются к содержимому невектора в индексе. В этом примере фильтр применяется к Tags полю для фильтрации всех отелей, которые не предоставляют бесплатный Wi-Fi.

  1. Вставьте запрос POST для запроса индекса поиска.

    ### 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. Проверьте ответ. Запрос совпадает с предыдущим примером, но он включает фильтр исключения после обработки и возвращает только три отеля, которые имеют бесплатный Wi-Fi.

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

Гибридный поиск состоит из ключевое слово запросов и векторных запросов в одном запросе поиска. В этом примере выполняется векторный запрос и полнотекстовый поиск одновременно:

  • Строка поиска: historic hotel walk to restaurants and shopping
  • Строка векторного запроса (векторизованная в математическое представление): classic lodging near running trails, eateries, retail
  1. Вставьте запрос POST для запроса индекса поиска. Затем нажмите кнопку "Отправить запрос".

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

    Так как это гибридный запрос, результаты ранжируются по RRF. RRF оценивает оценки поиска нескольких результатов поиска, принимает обратное, а затем объединяет и сортирует объединенные результаты. Возвращается top количество результатов.

  2. Проверьте ответ.

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

    Так как RRF объединяет результаты, он помогает просматривать входные данные. Ниже приведены результаты только полнотекстового запроса. Первые два результата : Sublime Cliff Hotel и History Lion Resort. Отель Sublime Cliff имеет более сильную оценку релевантности BM25.

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

    В запросе только для вектора, который использует HNSW для поиска совпадений, отель Sublime Cliff удаляется на четвертую позицию. Исторический лев, который был вторым в полнотекстовом поиске и третьем в векторном поиске, не имеет того же диапазона колебания, поэтому он отображается в качестве верхнего совпадения в однородном результирующем наборе.

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

Семантический гибридный поиск с фильтром

Ниже приведен последний запрос в коллекции. Этот гибридный запрос с семантической ранжированием фильтруется, чтобы показать только отели в радиусе 500 километров от Вашингтона. Можно задать vectorFilterMode значение NULL, что эквивалентно умолчанию (preFilter для более новых индексов и postFilter для старых).

  1. Вставьте запрос POST для запроса индекса поиска. Затем нажмите кнопку "Отправить запрос".

    ### 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. Проверьте ответ. Ответ равен трем отелям, которые фильтруются по расположению и семантически StateProvince переназначаются для повышения результатов, которые ближе всего к запросу строки поиска (historic hotel walk to restaurants and shopping).

    Старый отель Carabelle теперь движется в верхней точке. Без семантического ранжирования отель Нордик номер один. С семантического ранжирования модели машинного понимания признают, что historic относится к "отель, в пределах ходьбы от столовой (ресторанов) и покупок".

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

    Основные моменты:

    • Поиск вектора vectors.value определяется с помощью свойства. Поиск по ключевому слову search определяется с помощью свойства.
    • В гибридном поиске можно интегрировать векторный поиск с полнотекстовый поиск по ключевое слово. Фильтры, орфографические проверка и семантический ранжирование применяются только к текстовому содержимому, а не к векторам. В этом окончательном запросе нет семантики answer , так как система не получила достаточно сильного.
    • Фактические результаты включают более подробные сведения, включая семантические подпись и выделения. Результаты были изменены для удобства чтения. Чтобы получить полную структуру ответа, выполните запрос в клиенте REST.

Очистка

Если вы работаете в собственной подписке, в конце проекта следует решить, нужны ли вам созданные ресурсы. Ресурсы, которые продолжат работать, могут быть платными. Вы можете удалить ресурсы по отдельности либо удалить всю группу ресурсов.

Вы можете найти ресурсы на портале и управлять ими, используя ссылку "Все ресурсы" или "Группы ресурсов" в левой области.

Вы также можете попробовать следующую 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}}

Следующие шаги

На следующем шаге рекомендуется просмотреть демонстрационный код для Python, C#или JavaScript.