Snabbstart: Vektorsökning med hjälp av REST
Lär dig hur du använder REST API:er för sökning för att skapa, läsa in och fråga vektorer i Azure AI Search.
I Azure AI Search har ett vektorlager ett indexschema som definierar vektor- och icke-vektorfält, en vektorsökningskonfiguration för algoritmer som skapar inbäddningsutrymmet och inställningar för vektorfältdefinitioner som utvärderas vid frågetillfället. REST-API:et Skapa index skapar vektorarkivet.
Om du inte har någon Azure-prenumeration skapar du ett kostnadsfritt konto innan du börjar.
Kommentar
Den här snabbstarten utelämnar vektoriseringssteget och tillhandahåller inbäddningar i exempeldokument. Om du vill lägga till inbyggd datasegmentering och vektorisering över ditt eget innehåll kan du prova guiden Importera och vektorisera data för en genomgång från slutpunkt till slutpunkt.
Förutsättningar
Visual Studio Code med en REST-klient.
Azure AI Search, i valfri region och på valfri nivå. Skapa eller hitta en befintlig Azure AI Search-resurs under din aktuella prenumeration.
- Du kan använda den kostnadsfria nivån under större delen av den här snabbstarten, men Basic eller senare rekommenderas för större datafiler.
- Om du vill köra frågeexemplet som anropar semantisk omrankning måste söktjänsten vara basic-nivån eller högre, med semantisk rankning aktiverad.
Hämta resursinformation
Begäranden till sökslutpunkten måste autentiseras och auktoriseras. Du kan använda API-nycklar eller roller för den här uppgiften. Vi rekommenderar att du använder en nyckellös anslutning via Microsoft Entra-ID.
Välj den flik som motsvarar den autentiseringsmetod du föredrar. Använd samma metod för alla begäranden i den här snabbstarten.
Logga in på Azure Portal och hitta söktjänsten.
På startsidan Översikt hittar du URL:en. Här följer ett exempel på hur en slutpunkt kan se ut:
https://mydemo.search.windows.net
.Följ stegen i den nyckellösa snabbstarten för att hämta din Microsoft Entra-token.
Du får token när du kör
az account get-access-token
kommandot i steg 3 i föregående snabbstart.az account get-access-token --scope https://search.azure.com/.default --query accessToken --output tsv
Skapa eller ladda ned kodfilen
Du använder en fil eller .http
en .rest
fil för att köra alla begäranden i den här snabbstarten. Du kan ladda ned REST-filen som innehåller koden för den här snabbstarten, eller så kan du skapa en ny fil i Visual Studio Code och kopiera koden till den.
I Visual Studio Code skapar du en ny fil med filnamnstillägget
.rest
eller.http
filnamnstillägget. Exempel:az-search-vector-quickstart.rest
Kopiera och klistra in råinnehållet i filen Azure-Samples/azure-search-rest-samples/blob/main/Quickstart-vectors/az-search-vector-quickstart.rest i den här nya filen.Överst i filen ersätter du platshållarvärdet för
@baseUrl
med söktjänstens URL. Se avsnittet Hämta resursinformation för anvisningar om hur du hittar söktjänstens URL.@baseUrl = PUT-YOUR-SEARCH-SERVICE-URL-HERE
Överst i filen ersätter du platshållarvärdet för autentisering. Se avsnittet Hämta resursinformation för anvisningar om hur du hämtar din Microsoft Entra-token eller API-nyckel.
För den rekommenderade nyckellösa autentiseringen via Microsoft Entra-ID måste du ersätta
@apiKey
med variabeln@token
.@token = PUT-YOUR-MICROSOFT-ENTRA-TOKEN-HERE
Om du föredrar att använda en API-nyckel ersätter
@apiKey
du med nyckeln som du kopierade från Azure Portal.@apiKey = PUT-YOUR-ADMIN-KEY-HERE
För den rekommenderade nyckellösa autentiseringen via Microsoft Entra-ID måste du ersätta
api-key: {{apiKey}}
medAuthorization: Bearer {{token}}
i begärandehuvudena. Ersätt alla instanser avapi-key: {{apiKey}}
som du hittar i filen.
Skapa ett vektorindex
Du använder REST-API:et Skapa index för att skapa ett vektorindex och konfigurera de fysiska datastrukturerna i söktjänsten.
Indexschemat i det här exemplet är organiserat kring hotellinnehåll. Exempeldata består av vektor- och icke-bevektornamn och beskrivningar av fiktiva hotell. Det här schemat innehåller konfigurationer för vektorindexering och frågor samt för semantisk rangordning.
Öppna filen
az-search-vector-quickstart.rest
som du skapade tidigare i Visual Studio Code.Leta upp kodblocket
### Create a new index
i filen. Det här blocket innehåller begäran om att skapa indexet förhotels-vector-quickstart
söktjänsten.### 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" } ] } } ] } }
Välj Skicka begäran. Du bör ha ett
HTTP/1.1 201 Created
svar.
Svarstexten bör innehålla JSON-representationen av indexschemat.
{
"@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"
}
]
}
}
]
}
}
Viktiga lärdomar om REST API för att skapa index :
Samlingen
fields
innehåller ett obligatoriskt nyckelfält och text- och vektorfält (till exempelDescription
ochDescriptionVector
) för text- och vektorsökning. Genom att samlokalisera vektor- och icke-bevektorfält i samma index kan du använda hybridfrågor. Du kan till exempel kombinera filter, textsökning med semantisk rangordning och vektorer i en enda frågeåtgärd.Vektorfält måste vara
type: Collection(Edm.Single)
meddimensions
ochvectorSearchProfile
egenskaper.Avsnittet
vectorSearch
är en matris med ungefärliga konfigurationer och profiler för närliggande algoritmer. Algoritmer som stöds är hierarkisk navigeringsbar liten värld och fullständig k-närmaste granne. Mer information finns i Relevansbedömning i vektorsökning.Konfigurationen (valfritt)
semantic
gör det möjligt att ändra rangordning av sökresultat. Du kan ändra rangordningen av resultat i frågor av typensemantic
för strängfält som anges i konfigurationen. Mer information finns i Översikt över semantisk rangordning.
Ladda upp dokument
Att skapa och läsa in indexet är separata steg. Du skapade indexschemat i föregående steg. Nu måste du läsa in dokument i indexet.
I Azure AI Search innehåller indexet alla sökbara data och frågor som körs i söktjänsten. För REST-anrop tillhandahålls data som JSON-dokument. Använd Documents – Index REST API för den här uppgiften. URI:n utökas till att omfatta docs
samlingen och åtgärden index
.
Öppna filen
az-search-vector-quickstart.rest
som du skapade tidigare i Visual Studio Code.Leta upp kodblocket
### Upload documents
i filen. Det här blocket innehåller begäran om att ladda upp dokument till indexethotels-vector-quickstart
i söktjänsten.### 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" ] } ] }
Viktigt!
Koden i det här exemplet kan inte köras. Flera tecken eller rader tas bort för korthet. Använd koden i
az-search-vector-quickstart.rest
filen för att köra begäran.Välj Skicka begäran. Du bör ha ett
HTTP/1.1 200 OK
svar. Svarstexten bör innehålla JSON-representationen av sökdokumenten.
Viktiga lärdomar om begäran om Dokument – Index-REST API :
Dokument i nyttolasten består av fält som definierats i indexschemat.
Vektorfält innehåller flyttalsvärden. Dimensionsattributet har minst 2 och högst 3 072 flyttalsvärden vardera. Den här snabbstarten anger dimensionsattributet till 1 536 eftersom det är storleken på inbäddningar som genereras av Azure OpenAI-modellen textinbäddning-ada-002 .
Köra frågor
Nu när dokument har lästs in kan du skicka vektorfrågor mot dem med hjälp av Dokument – Sök efter (REST).
I nästa avsnitt kör vi frågor mot indexet hotels-vector-quickstart
. Frågorna omfattar:
Exempelvektorfrågorna baseras på två strängar:
-
Söksträng:
historic hotel walk to restaurants and shopping
-
Vektorfrågesträng (vektoriserad i en matematisk representation):
classic lodging near running trails, eateries, retail
Vektorfrågesträngen liknar söksträngen semantiskt, men den innehåller termer som inte finns i sökindexet. Om du gör en nyckelordssökning för classic lodging near running trails, eateries, retail
är resultatet noll. Vi använder det här exemplet för att visa hur du kan få relevanta resultat även om det inte finns några matchande termer.
Enkel vektorsökning
Öppna filen
az-search-vector-quickstart.rest
som du skapade tidigare i Visual Studio Code.Leta upp kodblocket
### Run a single vector query
i filen. Det här blocket innehåller begäran om att köra frågor mot sökindexet.### 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 } ] }
Den här vektorfrågan förkortas för korthet. Innehåller
vectorQueries.vector
den vektoriserade texten i frågeindata,fields
avgör vilka vektorfält som söks ochk
anger antalet närmaste grannar som ska returneras.Vektorfrågesträngen är
classic lodging near running trails, eateries, retail
, som är vektoriserad i 1 536 inbäddningar för den här frågan.Viktigt!
Koden i det här exemplet kan inte köras. Flera tecken eller rader tas bort för korthet. Använd koden i
az-search-vector-quickstart.rest
filen för att köra begäran.Välj Skicka begäran. Du bör ha ett
HTTP/1.1 200 OK
svar. Svarstexten bör innehålla JSON-representationen av sökresultaten.
Svaret för vektorekvivalenten för classic lodging near running trails, eateries, retail
innehåller sju resultat. Varje resultat ger en sökpoäng och fälten som anges i select
. I en likhetssökning innehåller k
svaret alltid resultat ordnade efter värdets likhetspoäng.
{
"@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"
}
]
}
Enkel vektorsökning med filter
Du kan lägga till filter, men filtren tillämpas på icke-bevektorinnehållet i ditt index. I det här exemplet gäller filtret för fältet Tags
för att filtrera bort alla hotell som inte tillhandahåller kostnadsfritt Wi-Fi.
Öppna filen
az-search-vector-quickstart.rest
som du skapade tidigare i Visual Studio Code.Leta upp kodblocket
### Run a vector query with a filter
i filen. Det här blocket innehåller begäran om att köra frågor mot sökindexet.### 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 }, ] }
Viktigt!
Koden i det här exemplet kan inte köras. Flera tecken eller rader tas bort för korthet. Använd koden i
az-search-vector-quickstart.rest
filen för att köra begäran.Välj Skicka begäran. Du bör ha ett
HTTP/1.1 200 OK
svar. Svarstexten bör innehålla JSON-representationen av sökresultaten.
Frågan var densamma som i föregående exempel på enkel vektorsökning, men den innehåller ett exkluderingsfilter efter bearbetning och returnerar endast de tre hotell som har kostnadsfritt Wi-Fi.
{
"@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"
]
}
]
}
Hybridsökning
Hybridsökning består av nyckelordsfrågor och vektorfrågor i en enda sökbegäran. I det här exemplet körs vektorfrågan och fulltextsökning samtidigt:
-
Söksträng:
historic hotel walk to restaurants and shopping
-
Vektorfrågesträng (vektoriserad i en matematisk representation):
classic lodging near running trails, eateries, retail
Öppna filen
az-search-vector-quickstart.rest
som du skapade tidigare i Visual Studio Code.Leta upp kodblocket
### Run a hybrid query
i filen. Det här blocket innehåller begäran om att köra frågor mot sökindexet.### 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 } ] }
Viktigt!
Koden i det här exemplet kan inte köras. Flera tecken eller rader tas bort för korthet. Använd koden i
az-search-vector-quickstart.rest
filen för att köra begäran.Välj Skicka begäran. Du bör ha ett
HTTP/1.1 200 OK
svar. Svarstexten bör innehålla JSON-representationen av sökresultaten.
Eftersom det här är en hybridfråga rangordnas resultaten efter Reciprocal Rank Fusion (RRF). RRF utvärderar sökpoäng för flera sökresultat, tar inversen och sammanfogar och sorterar sedan de kombinerade resultaten. Antalet top
resultat returneras.
Granska svaret:
{
"@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."
}
]
}
Eftersom RRF sammanfogar resultat hjälper det att granska indata. Följande resultat kommer endast från fulltextfrågan. De två främsta resultaten är Sublime Palace Hotel och History Lion Resort. Sublime Palace Hotel har en starkare BM25 relevanspoäng.
{
"@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"
},
I frågan med endast vektorer, som använder HNSW för att hitta matchningar, sjunker Sublime Palace Hotel till fjärde plats. Historic Lion, som var tvåa i fulltextsökningen och tredje i vektorsökningen, upplever inte samma fluktuationsintervall, så det visas som en toppmatchning i en homogeniserad resultatuppsättning.
"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"
}
]
Semantisk hybridsökning med ett filter
Här är den sista frågan i samlingen. Den här hybridfrågan med semantisk rangordning filtreras för att endast visa hotellen inom en radie på 500 kilometer från Washington D.C. Du kan ange vectorFilterMode
null, vilket motsvarar standardvärdet (preFilter
för nyare index och postFilter
för äldre index).
Öppna filen
az-search-vector-quickstart.rest
som du skapade tidigare i Visual Studio Code.Leta upp kodblocket
### Run a hybrid query with semantic reranking
i filen. Det här blocket innehåller begäran om att köra frågor mot sökindexet.### 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 } ] }
Viktigt!
Koden i det här exemplet kan inte köras. Flera tecken eller rader tas bort för korthet. Använd koden i
az-search-vector-quickstart.rest
filen för att köra begäran.Välj Skicka begäran. Du bör ha ett
HTTP/1.1 200 OK
svar. Svarstexten bör innehålla JSON-representationen av sökresultaten.
Läs svaret. Svaret är tre hotell, som filtreras efter plats och fasetteras av StateProvince
och semantiskt rangordnas om för att höja upp resultat som är närmast söksträngsfrågan (historic hotel walk to restaurants and shopping
).
The Swirling Currents Hotel går nu in på topplaceringen. Utan semantisk ranking är Nordick's Valley Motel nummer ett. Med semantisk rankning känner maskinförståelsemodellerna igen som historic
gäller för "hotell, inom gångavstånd till restauranger och shopping.".
{
"@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
}
}
]
}
Viktiga lärdomar om dokument – Sök efter REST API:
Vektorsökning anges via egenskapen
vectors.value
. Nyckelordssökning anges via egenskapensearch
.I en hybridsökning kan du integrera vektorsökning med fulltextsökning över nyckelord. Filter, stavningskontroll och semantisk rangordning gäller endast för textinnehåll och inte vektorer. I den här sista frågan finns det ingen semantisk
answer
eftersom systemet inte har skapat en som var tillräckligt stark.Faktiska resultat innehåller mer information, inklusive semantiska bildtexter och markeringar. Resultaten ändrades för läsbarhet. Kör begäran i REST-klienten för att få hela strukturen för svaret.
Rensa
När du arbetar i din egen prenumeration kan det dock vara klokt att i slutet av ett projekt kontrollera om du fortfarande behöver de resurser som du skapade. Resurser som fortsätter att köras kostar pengar. Du kan ta bort enstaka resurser eller hela resursgruppen om du vill ta bort alla resurser.
Du kan hitta och hantera resurser i Azure Portal med hjälp av länken Alla resurser eller Resursgrupper i den vänstra rutan.
Om du vill behålla söktjänsten, men ta bort indexet och dokumenten, kan du använda DELETE
kommandot i REST-klienten. Det här kommandot (i slutet av az-search-vector-quickstart.rest
filen) tar bort indexet 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}}
Nästa steg
Som nästa steg rekommenderar vi att du lär dig hur du anropar REST API-anrop utan API-nycklar.
Du kanske också vill granska demokoden för Python, C#eller JavaScript.