SearchClient Class
- java.
lang. Object - com.
azure. search. documents. SearchClient
- com.
public final class SearchClient
This class provides a client that contains the operations for querying an index and uploading, merging, or deleting documents in an Azure AI Search service.
Overview
Conceptually, a document is an entity in your index. Mapping this concept to more familiar database equivalents: a search index equates to a table, and documents are roughly equivalent to rows in a table. Documents exist only in an index, and are retrieved only through queries that target the documents collection (/docs) of an index. All operations performed on the collection such as uploading, merging, deleting, or querying documents take place in the context of a single index, so the URL format document operations will always include /indexes/[index name]/docs for a given index name.
This client provides a synchronous API for accessing and performing operations on indexed documents. This client assists with searching your indexed documents, autocompleting partially typed search terms based on documents within the index, suggesting the most likely matching text in documents as a user types. The client provides operations for adding, updating, and deleting documents from an index.
Getting Started
Authenticating and building instances of this client are handled by SearchClientBuilder. This sample shows you how to authenticate and create an instance of the client:
SearchClient searchClient = new SearchClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.indexName("{indexName}")
.buildClient();
For more information on authentication and building, see the SearchClientBuilder documentation.
Examples
The following examples all use a simple Hotel data set that you can import into your own index from the Azure portal. These are just a few of the basics - please check out our Samples for much more.
Upload a Document
The following sample uploads a new document to an index.
List<Hotel> hotels = new ArrayList<>();
hotels.add(new Hotel().setHotelId("100"));
hotels.add(new Hotel().setHotelId("200"));
hotels.add(new Hotel().setHotelId("300"));
searchClient.uploadDocuments(hotels);
For an asynchronous sample see uploadDocuments(Iterable<?> documents).
Merge a Document
The following sample merges documents in an index.
List<Hotel> hotels = new ArrayList<>();
hotels.add(new Hotel().setHotelId("100"));
hotels.add(new Hotel().setHotelId("200"));
searchClient.mergeDocuments(hotels);
For an asynchronous sample see mergeDocuments(Iterable<?> documents).
Delete a Document
The following sample deletes a document from an index.
SearchDocument documentId = new SearchDocument();
documentId.put("hotelId", "100");
searchClient.deleteDocuments(Collections.singletonList(documentId));
For an asynchronous sample see deleteDocuments(Iterable<?> documents).
Get a Document
The following sample gets a document from an index.
Hotel hotel = searchClient.getDocument("100", Hotel.class);
System.out.printf("Retrieved Hotel %s%n", hotel.getHotelId());
For an asynchronous sample see getDocument(String key, Class<T> modelClass).
Search Documents
The following sample searches for documents within an index.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelId", "8");
searchDocument.put("description", "budget");
searchDocument.put("descriptionFr", "motel");
SearchDocument searchDocument1 = new SearchDocument();
searchDocument1.put("hotelId", "9");
searchDocument1.put("description", "budget");
searchDocument1.put("descriptionFr", "motel");
List<SearchDocument> searchDocuments = new ArrayList<>();
searchDocuments.add(searchDocument);
searchDocuments.add(searchDocument1);
searchClient.uploadDocuments(searchDocuments);
SearchPagedIterable results = searchClient.search("SearchText");
System.out.printf("There are %s results.%n", results.getTotalCount());
For an asynchronous sample see search(String searchText).
Make a Suggestion
The following sample suggests the most likely matching text in documents.
SuggestPagedIterable suggestPagedIterable = searchClient.suggest("searchText", "sg");
for (SuggestResult result: suggestPagedIterable) {
System.out.printf("The suggested text is %s", result.getText());
}
For an asynchronous sample see suggest(String searchText, String suggesterName).
Provide an Autocompletion
The following sample provides autocompletion for a partially typed query.
AutocompletePagedIterable autocompletePagedIterable = searchClient.autocomplete("searchText", "sg");
for (AutocompleteItem result: autocompletePagedIterable) {
System.out.printf("The complete term is %s", result.getText());
}
For an asynchronous sample see autocomplete(String searchText, String suggesterName).
Method Summary
Methods inherited from java.lang.Object
Method Details
getDocument
public T
Retrieves a document from the Azure AI Search index.
View naming rules for guidelines on constructing valid document keys.
Code Sample
Get dynamic SearchDocument.
SearchDocument result = SEARCH_CLIENT.getDocument("hotelId", SearchDocument.class);
for (Map.Entry<String, Object> keyValuePair : result.entrySet()) {
System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), keyValuePair.getValue());
}
Parameters:
Returns:
getDocumentWithResponse
public Response
Retrieves a document from the Azure AI Search index.
View naming rules for guidelines on constructing valid document keys.
Code Sample
Get dynamic SearchDocument.
Response<SearchDocument> resultResponse = SEARCH_CLIENT.getDocumentWithResponse("hotelId",
SearchDocument.class, null, new Context(KEY_1, VALUE_1));
System.out.println("The status code of the response is " + resultResponse.getStatusCode());
for (Map.Entry<String, Object> keyValuePair : resultResponse.getValue().entrySet()) {
System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), keyValuePair.getValue());
}
Parameters:
Returns:
autocomplete
public AutocompletePagedIterable autocomplete(String searchText, String suggesterName)
Autocompletes incomplete query terms based on input text and matching terms in the index.
Code Sample
Autocomplete text from documents in service.
AutocompletePagedIterable autocompletePagedIterable = SEARCH_CLIENT.autocomplete("searchText", "sg");
for (AutocompleteItem result: autocompletePagedIterable) {
System.out.printf("The complete term is %s", result.getText());
}
Parameters:
Returns:
autocomplete
public AutocompletePagedIterable autocomplete(String searchText, String suggesterName, AutocompleteOptions autocompleteOptions, Context context)
Autocompletes incomplete query terms based on input text and matching terms in the index.
Code Sample
Autocomplete text from documents in service with option.
AutocompletePagedIterable autocompletePagedIterable = SEARCH_CLIENT.autocomplete("searchText", "sg",
new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT),
new Context(KEY_1, VALUE_1));
for (AutocompleteItem result: autocompletePagedIterable) {
System.out.printf("The complete term is %s", result.getText());
}
Parameters:
Returns:
deleteDocuments
public IndexDocumentsResult deleteDocuments(Iterable documents)
Deletes a collection of documents from the target index.
Code Sample
Delete dynamic SearchDocument.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelId", "1");
searchDocument.put("hotelName", "test");
IndexDocumentsResult result = SEARCH_CLIENT.deleteDocuments(Collections.singletonList(searchDocument));
for (IndexingResult indexingResult : result.getResults()) {
System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
deleteDocumentsWithResponse
public Response
Deletes a collection of documents from the target index.
Code Sample
Delete dynamic SearchDocument.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelId", "1");
searchDocument.put("hotelName", "test");
Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.deleteDocumentsWithResponse(
Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1));
System.out.println("The status code of the response is " + resultResponse.getStatusCode());
for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
getDocumentCount
public long getDocumentCount()
Queries the number of documents in the search index.
Code Sample
Get document count.
long count = SEARCH_CLIENT.getDocumentCount();
System.out.printf("There are %d documents in service.", count);
Returns:
getDocumentCountWithResponse
public Response
Queries the number of documents in the search index.
Code Sample
Get document count.
Response<Long> countResponse = SEARCH_CLIENT.getDocumentCountWithResponse(new Context(KEY_1, VALUE_1));
System.out.println("The status code of the response is " + countResponse.getStatusCode());
System.out.printf("There are %d documents in service.", countResponse.getValue());
Parameters:
Returns:
getEndpoint
public String getEndpoint()
Gets the endpoint for the Azure AI Search service.
Returns:
getIndexName
public String getIndexName()
Gets the name of the Azure AI Search index.
Returns:
indexDocuments
public IndexDocumentsResult indexDocuments(IndexDocumentsBatch batch)
Sends a batch of upload, merge, and/or delete actions to the search index.
Code Sample
Index batch operation on dynamic SearchDocument.
SearchDocument searchDocument1 = new SearchDocument();
searchDocument1.put("hotelId", "1");
searchDocument1.put("hotelName", "test1");
SearchDocument searchDocument2 = new SearchDocument();
searchDocument2.put("hotelId", "2");
searchDocument2.put("hotelName", "test2");
IndexDocumentsBatch<SearchDocument> indexDocumentsBatch = new IndexDocumentsBatch<>();
indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1));
indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2));
IndexDocumentsResult result = SEARCH_CLIENT.indexDocuments(indexDocumentsBatch);
for (IndexingResult indexingResult : result.getResults()) {
System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
indexDocumentsWithResponse
public Response
Sends a batch of upload, merge, and/or delete actions to the search index.
Code Sample
Index batch operation on dynamic SearchDocument.
SearchDocument searchDocument1 = new SearchDocument();
searchDocument1.put("hotelId", "1");
searchDocument1.put("hotelName", "test1");
SearchDocument searchDocument2 = new SearchDocument();
searchDocument2.put("hotelId", "2");
searchDocument2.put("hotelName", "test2");
IndexDocumentsBatch<SearchDocument> indexDocumentsBatch = new IndexDocumentsBatch<>();
indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1));
indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2));
Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.indexDocumentsWithResponse(indexDocumentsBatch,
null, new Context(KEY_1, VALUE_1));
System.out.println("The status code of the response is " + resultResponse.getStatusCode());
for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
mergeDocuments
public IndexDocumentsResult mergeDocuments(Iterable documents)
Merges a collection of documents with existing documents in the target index.
If the type of the document contains non-nullable primitive-typed properties, these properties may not merge correctly. If you do not set such a property, it will automatically take its default value (for example, 0
for int
or false for boolean
), which will override the value of the property currently stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you always declare primitive-typed properties with their class equivalents (for example, an integer property should be of type Integer
instead of int
).
Code Sample
Merge dynamic SearchDocument.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelName", "merge");
IndexDocumentsResult result = SEARCH_CLIENT.mergeDocuments(Collections.singletonList(searchDocument));
for (IndexingResult indexingResult : result.getResults()) {
System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
mergeDocumentsWithResponse
public Response
Merges a collection of documents with existing documents in the target index.
If the type of the document contains non-nullable primitive-typed properties, these properties may not merge correctly. If you do not set such a property, it will automatically take its default value (for example, 0
for int
or false for boolean
), which will override the value of the property currently stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you always declare primitive-typed properties with their class equivalents (for example, an integer property should be of type Integer
instead of int
).
Code Sample
Merge dynamic SearchDocument.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelName", "test");
Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.mergeDocumentsWithResponse(
Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1));
System.out.println("The status code of the response is " + resultResponse.getStatusCode());
for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
mergeOrUploadDocuments
public IndexDocumentsResult mergeOrUploadDocuments(Iterable documents)
This action behaves like merge if a document with the given key already exists in the index. If the document does not exist, it behaves like upload with a new document.
If the type of the document contains non-nullable primitive-typed properties, these properties may not merge correctly. If you do not set such a property, it will automatically take its default value (for example, 0
for int
or false for boolean
), which will override the value of the property currently stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you always declare primitive-typed properties with their class equivalents (for example, an integer property should be of type Integer
instead of int
).
Code Sample
Merge or upload dynamic SearchDocument.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelId", "1");
searchDocument.put("hotelName", "test");
IndexDocumentsResult result = SEARCH_CLIENT.mergeOrUploadDocuments(Collections.singletonList(searchDocument));
for (IndexingResult indexingResult : result.getResults()) {
System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
mergeOrUploadDocumentsWithResponse
public Response
This action behaves like merge if a document with the given key already exists in the index. If the document does not exist, it behaves like upload with a new document.
If the type of the document contains non-nullable primitive-typed properties, these properties may not merge correctly. If you do not set such a property, it will automatically take its default value (for example, 0
for int
or false for boolean
), which will override the value of the property currently stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you always declare primitive-typed properties with their class equivalents (for example, an integer property should be of type Integer
instead of int
).
Code Sample
Merge or upload dynamic SearchDocument.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelId", "1");
searchDocument.put("hotelName", "test");
Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.mergeOrUploadDocumentsWithResponse(
Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1));
System.out.println("The status code of the response is " + resultResponse.getStatusCode());
for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
search
public SearchPagedIterable search(String searchText)
Searches for documents in the Azure AI Search index.
If searchText
is set to null or "*"
all documents will be matched, see simple query syntax in Azure AI Search for more information about search query syntax.
The SearchPagedIterable will iterate through search result pages until all search results are returned. Each page is determined by the $skip
and $top
values and the Search service has a limit on the number of documents that can be skipped, more information about the $skip
limit can be found at Search Documents REST API and reading the $skip
description. If the total number of results exceeds the $skip
limit the SearchPagedIterable won't prevent you from exceeding the $skip
limit. To prevent exceeding the limit you can track the number of documents returned and stop requesting new pages when the limit is reached.
Code Sample
Search text from documents in service.
SearchPagedIterable searchPagedIterable = SEARCH_CLIENT.search("searchText");
System.out.printf("There are around %d results.", searchPagedIterable.getTotalCount());
long numberOfDocumentsReturned = 0;
for (SearchPagedResponse resultResponse: searchPagedIterable.iterableByPage()) {
System.out.println("The status code of the response is " + resultResponse.getStatusCode());
numberOfDocumentsReturned += resultResponse.getValue().size();
resultResponse.getValue().forEach(searchResult -> {
for (Map.Entry<String, Object> keyValuePair: searchResult
.getDocument(SearchDocument.class).entrySet()) {
System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
keyValuePair.getValue());
}
});
if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) {
// Reached the $skip limit, stop requesting more documents.
break;
}
}
Parameters:
Returns:
search
public SearchPagedIterable search(String searchText, SearchOptions searchOptions, Context context)
Searches for documents in the Azure AI Search index.
If searchText
is set to null or "*"
all documents will be matched, see simple query syntax in Azure AI Search for more information about search query syntax.
The SearchPagedIterable will iterate through search result pages until all search results are returned. Each page is determined by the $skip
and $top
values and the Search service has a limit on the number of documents that can be skipped, more information about the $skip
limit can be found at Search Documents REST API and reading the $skip
description. If the total number of results exceeds the $skip
limit the SearchPagedIterable won't prevent you from exceeding the $skip
limit. To prevent exceeding the limit you can track the number of documents returned and stop requesting new pages when the limit is reached.
Code Sample
Search text from documents in service with option.
SearchPagedIterable searchPagedIterable = SEARCH_CLIENT.search("searchText",
new SearchOptions().setOrderBy("hotelId desc"), new Context(KEY_1, VALUE_1));
System.out.printf("There are around %d results.", searchPagedIterable.getTotalCount());
long numberOfDocumentsReturned = 0;
for (SearchPagedResponse resultResponse: searchPagedIterable.iterableByPage()) {
System.out.println("The status code of the response is " + resultResponse.getStatusCode());
numberOfDocumentsReturned += resultResponse.getValue().size();
resultResponse.getValue().forEach(searchResult -> {
for (Map.Entry<String, Object> keyValuePair: searchResult
.getDocument(SearchDocument.class).entrySet()) {
System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
keyValuePair.getValue());
}
});
if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) {
// Reached the $skip limit, stop requesting more documents.
break;
}
}
Parameters:
Returns:
suggest
public SuggestPagedIterable suggest(String searchText, String suggesterName)
Suggests documents in the index that match the given partial query.
Code Sample
Suggest text from documents in service.
SuggestPagedIterable suggestPagedIterable = SEARCH_CLIENT.suggest("searchText", "sg");
for (SuggestResult result: suggestPagedIterable) {
SearchDocument searchDocument = result.getDocument(SearchDocument.class);
for (Map.Entry<String, Object> keyValuePair: searchDocument.entrySet()) {
System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue());
}
}
Parameters:
Returns:
suggest
public SuggestPagedIterable suggest(String searchText, String suggesterName, SuggestOptions suggestOptions, Context context)
Suggests documents in the index that match the given partial query.
Code Sample
Suggest text from documents in service with option.
SuggestPagedIterable suggestPagedIterable = SEARCH_CLIENT.suggest("searchText", "sg",
new SuggestOptions().setOrderBy("hotelId desc"), new Context(KEY_1, VALUE_1));
for (SuggestResult result: suggestPagedIterable) {
SearchDocument searchDocument = result.getDocument(SearchDocument.class);
for (Map.Entry<String, Object> keyValuePair: searchDocument.entrySet()) {
System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue());
}
}
Parameters:
Returns:
uploadDocuments
public IndexDocumentsResult uploadDocuments(Iterable documents)
Uploads a collection of documents to the target index.
Code Sample
Upload dynamic SearchDocument.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelId", "1");
searchDocument.put("hotelName", "test");
IndexDocumentsResult result = SEARCH_CLIENT.uploadDocuments(Collections.singletonList(searchDocument));
for (IndexingResult indexingResult : result.getResults()) {
System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
uploadDocumentsWithResponse
public Response
Uploads a collection of documents to the target index.
Code Sample
Upload dynamic SearchDocument.
SearchDocument searchDocument = new SearchDocument();
searchDocument.put("hotelId", "1");
searchDocument.put("hotelName", "test");
Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.uploadDocumentsWithResponse(
Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1));
System.out.println("The status code of the response is " + resultResponse.getStatusCode());
for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(),
indexingResult.isSucceeded());
}
Parameters:
Returns:
Applies to
Azure SDK for Java