In my previous post, I discussed the process of establishing a Free-text search for Azure Cosmos DB. Towards the end, I demonstrated how to carry out a free-text search using the Azure Portal. Now, I will guide you on how to perform this search using code. To perform this search by code, I created a basic console application and added Azure.Search.Documents and Microsoft.Azure.Cosmos.
I will use the Azure Search service API to make a free-text search in the Azure Search index I created in my earlier post.. Here is the available fields of the index . As you can see, Title and the PostBody fields are searchable.
I have created a SearchResult class to handle the search results.
I have another function named Search which calls Azure Search and return the data.
To choose the fields you want to see, use the SearchOptions. In this instance, I wanted to view the total count and limited the results to 10 using the size parameter. The SearchAsync function is where the magic occurs. The application contacts Azure Search and retrieves the data. When I run the application, the following screen appears
You have the option to choose from a list of items returned by Azure Search Engine. Azure Search has identified 146692 results when searching for SQL Server. It used Title and the PostBody to find these results. Each option includes a document ID and partition key which I don't display on UI. Once you select an item, I can retrieve the document using the cost-effective Point Read function of Azure Cosmos DB.
I use the ReadItemStreamAsync function to retrieve the selected document. This function requires document's id and the partition key.
For my example, I chose the number 5. The application then sent the document ID and partition key to the Search function. Using Azure Cosmos DB, I conducted a Point Read search and retrieved the entire document. The Point Read function only used 1.05 Request Units.
No comments:
Post a Comment