azure-docs-sdk-java/docs-ref-autogen/com.azure.search.documents.yml

21 строка
21 KiB
YAML

### YamlMime:JavaPackage
uid: "com.azure.search.documents"
fullName: "com.azure.search.documents"
name: "com.azure.search.documents"
summary: "[Azure AI Search][], formerly known as \"Azure AI Search\", provides secure information retrieval at scale over user-owned content in traditional and conversational search applications.\n\n\n[Azure AI Search]: https://learn.microsoft.com/azure/search/"
classes:
- "com.azure.search.documents.SearchAsyncClient"
- "com.azure.search.documents.SearchClient"
- "com.azure.search.documents.SearchClientBuilder"
- "com.azure.search.documents.SearchClientBuilder.SearchIndexingBufferedSenderBuilder"
- "com.azure.search.documents.SearchDocument"
- "com.azure.search.documents.SearchFilter"
- "com.azure.search.documents.SearchIndexingBufferedAsyncSender"
- "com.azure.search.documents.SearchIndexingBufferedSender"
enums:
- "com.azure.search.documents.SearchServiceVersion"
desc: "[Azure AI Search][], formerly known as \"Azure AI Search\", provides secure information retrieval at scale over user-owned content in traditional and conversational search applications.\n\nThe Azure AI Search service provides:/p>\n\n * A search engine for vector search, full text, and hybrid search over a search index.\n * Rich indexing with integrated data chunking and vectorization (preview), lexical analysis for text, and optional AI enrichment for content extraction and transformation.\n * Rich query syntax for vector queries, text search, hybrid queries, fuzzy search, autocomplete, geo-search and others.\n * Azure scale, security, and reach.\n * Azure integration at the data layer, machine learning layer, Azure AI services and Azure OpenAI\n\nThe Azure AI Search service is well suited for the following application scenarios:\n\n * Consolidate varied content types into a single searchable index. To populate an index, you can push JSON documents that contain your content, or if your data is already in Azure, create an indexer to pull in data automatically.\n * Attach skillsets to an indexer to create searchable content from images and large text documents. A skillset leverages AI from Cognitive Services for built-in OCR, entity recognition, key phrase extraction, language detection, text translation, and sentiment analysis. You can also add custom skills to integrate external processing of your content during data ingestion.\n * In a search client application, implement query logic and user experiences similar to commercial web search engines.\n\nThis is the Java client library for Azure AI Search. Azure AI Search service is a search-as-a-service cloud solution that gives developers APIs and tools for adding a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications.\n\nThe Azure Search Documents client library allows for Java developers to easily interact with the Azure AI Search service from their Java applications. This library provides a set of APIs that abstract the low-level details of working with the Azure AI Search service and allows developers to perform common operations such as:\n\n * Submit queries for simple and advanced query forms that include fuzzy search, wildcard search, regular expressions..\n * Implement filtered queries for faceted navigation, geospatial search, or to narrow results based on filter criteria.\n * Create and manage search indexes.\n * Upload and update documents in the search index.\n * Create and manage indexers that pull data from Azure into an index.\n * Create and manage skillsets that add AI enrichment to data ingestion.\n * Create and manage analyzers for advanced text analysis or multi-lingual content.\n * Optimize results through scoring profiles to factor in business logic or freshness.\n\n## Getting Started ##\n\n### Prerequisites ###\n\nThe client library package requires the following:\n\n * Java Development Kit (JDK) 8 or later\n * [An Azure subscription][]\n * [An existing Azure AI Search service][]\n\n*To create a new Search service, you can use the [Azure portal][], [Azure Powershell][], or the [Azure CLI.][]*\n\n### Authenticate the client ###\n\nTo interact with the Search service, you'll need to create an instance of the appropriate client class: SearchClient for searching indexed documents, SearchIndexClient for managing indexes, or SearchIndexerClient for crawling data sources and loading search documents into an index. To instantiate a client object, you'll need an endpoint and API key. You can refer to the documentation for more information on [supported authenticating approaches][] with the Search service.\n\n#### Get an API Key ####\n\nYou can get the endpoint and an API key from the Search service in the [Azure Portal.][] Please refer [the documentation][] for instructions on how to get an API key.\n\nThe SDK provides three clients.\n\n * SearchIndexClient for CRUD operations on indexes and synonym maps.\n * SearchIndexerClient for CRUD operations on indexers, data sources, and skillsets.\n * SearchClient for all document operations.\n\n### Create a SearchIndexClient ###\n\nTo create a SearchIndexClient, you will need the values of the Azure AI Search service URL endpoint and admin key. The following snippet shows how to create a SearchIndexClient.\n\nThe following sample creates a SearchIndexClient using the endpoint and Azure Key Credential (API Key).\n\n```java\nSearchIndexClient searchIndexClient = new SearchIndexClientBuilder()\n .endpoint(\"{endpoint}\")\n .credential(new AzureKeyCredential(\"{key}\"))\n .buildClient();\n```\n\n### Create a SearchIndexerClient ###\n\nTo create a SearchIndexerClient, you will need the values of the Azure AI Search service URL endpoint and admin key. The following snippet shows how to create a SearchIndexerClient.\n\nThe following sample creates SearchIndexerClient using an endpoint and Azure Key Credential (API Key).\n\n```java\nSearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder()\n .endpoint(\"{endpoint}\")\n .credential(new AzureKeyCredential(\"{key}\"))\n .buildClient();\n```\n\n### Create a SearchClient ###\n\nTo create a SearchClient, you will need the values of the Azure AI Search service URL endpoint, admin key, and an index name. The following snippet shows how to create a SearchIndexerClient.\n\nThe following sample creates a SearchClient\n\n```java\nSearchClient searchClient = new SearchClientBuilder()\n .endpoint(\"{endpoint}\")\n .credential(new AzureKeyCredential(\"{key}\"))\n .indexName(\"{indexName}\")\n .buildClient();\n```\n\n## Key Concepts ##\n\nAn Azure AI Search service contains one or more indexes that provide persistent storage of searchable data in the form of JSON documents. (If you're new to search, you can make a very rough analogy between indexes and database tables.) The azure-search-documents client library exposes operations on these resources through two main client types.\n\nSearchClient helps with:\n\n * [Searching][] your indexed documents using [rich queries][] and [powerful data shaping.][]\n * [Autocompleting][] partially typed search terms based on documents in the index.\n * [Suggesting][] the most likely matching text in documents as a user types.\n * [Adding, Updating or Deleting][Adding_ Updating or Deleting] documents from an index.\n\nSearchIndexClient allows you to:\n\n * Create, delete, update, or configure a search index\n * Declare custom synonym maps to expand or rewrite queries\n * Most of the SearchServiceClient functionality is not yet available in our current preview\n\nSearchIndexerClient allows you to:\n\n * Start indexers to automatically crawl data sources\n * Define AI powered Skillsets to transform and enrich your data\n\nAzure AI Search provides two powerful features:\n\n### Semantic Search ###\n\nSemantic search enhances the quality of search results for text-based queries. By enabling Semantic Search on your search service, you can improve the relevance of search results in two ways:\n\n * It applies secondary ranking to the initial result set, promoting the most semantically relevant results to the top.\n * It extracts and returns captions and answers in the response, which can be displayed on a search page to enhance the user's search experience.\n\nTo learn more about Semantic Search, you can refer to the documentation.\n\n### Vector Search ###\n\nVector Search is an information retrieval technique that overcomes the limitations of traditional keyword-based search. Instead of relying solely on lexical analysis and matching individual query terms, Vector Search utilizes machine learning models to capture the contextual meaning of words and phrases. It represents documents and queries as vectors in a high-dimensional space called an embedding. By understanding the intent behind the query, Vector Search can deliver more relevant results that align with the user's requirements, even if the exact terms are not present in the document. Moreover, Vector Search can be applied to various types of content, including images and videos, not just text.\n\nTo learn how to index vector fields and perform vector search, you can refer to the [sample][]. This sample provides detailed guidance on indexing vector fields and demonstrates how to perform vector search.\n\nAdditionally, for more comprehensive information about Vector Search, including its concepts and usage, you can refer to the [documentation][]. The documentation provides in-depth explanations and guidance on leveraging the power of Vector Search in Azure AI Search.\n\n### Examples ###\n\nThe following examples all use a sample[ Hotel data set][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.\n\n#### Querying ####\n\nThere are two ways to interact with the data returned from a search query.\n\n##### Use SearchDocument like a dictionary for search results #####\n\nSearchDocument is the default type returned from queries when you don't provide your own. The following sample performs the search, enumerates over the results, and extracts data using SearchDocument's dictionary indexer.\n\n```java\nfor (SearchResult result : searchClient.search(\"luxury\")) {\n SearchDocument document = result.getDocument(SearchDocument.class);\n System.out.printf(\"Hotel ID: %s%n\", document.get(\"hotelId\"));\n System.out.printf(\"Hotel Name: %s%n\", document.get(\"hotelName\"));\n }\n```\n\n##### Use Java model class for search results #####\n\nDefine a \\`Hotel\\` class.\n\n```java\npublic static class Hotel {\n private String hotelId;\n private String hotelName;\n\n @SimpleField(isKey = true)\n public String getHotelId() {\n return this.hotelId;\n }\n\n public String getHotelName() {\n return this.hotelName;\n }\n\n public Hotel setHotelId(String number) {\n this.hotelId = number;\n return this;\n }\n\n public Hotel setHotelName(String secretPointMotel) {\n this.hotelName = secretPointMotel;\n return this;\n }\n }\n```\n\nUse it in place of SearchDocument when querying.\n\n```java\nfor (SearchResult result : searchClient.search(\"luxury\")) {\n Hotel hotel = result.getDocument(Hotel.class);\n System.out.printf(\"Hotel ID: %s%n\", hotel.getHotelId());\n System.out.printf(\"Hotel Name: %s%n\", hotel.getHotelName());\n }\n```\n\n##### Search Options #####\n\nThe SearchOptions provide powerful control over the behavior of our queries.\n\nThe following sample uses SearchOptions to search for the top 5 luxury hotel with a good rating (4 or above).\n\n```java\nSearchOptions options = new SearchOptions()\n .setFilter(\"rating gt 4\")\n .setOrderBy(\"rating desc\")\n .setTop(5);\n SearchPagedIterable searchResultsIterable = searchClient.search(\"luxury\", options, Context.NONE);\n searchResultsIterable.forEach(result -> {\n System.out.printf(\"Hotel ID: %s%n\", result.getDocument(Hotel.class).getHotelId());\n System.out.printf(\"Hotel Name: %s%n\", result.getDocument(Hotel.class).getHotelName());\n });\n```\n\n#### Creating an index ####\n\nYou can use the SearchIndexClient to create a search index. Indexes can also define suggesters, lexical analyzers, and more.\n\nThere are multiple ways of preparing search fields for a search index. For basic needs, there is a static helper method buildSearchFields in SearchIndexClient and SearchIndexAsyncClient. There are three annotations SimpleFieldProperty, SearchFieldProperty and FieldBuilderIgnore to configure the field of model class.\n\n```java\n// Create a new search index structure that matches the properties of the Hotel class.\n List<SearchField> searchFields = SearchIndexClient.buildSearchFields(Hotel.class, null);\n searchIndexClient.createIndex(new SearchIndex(\"hotels\", searchFields));\n```\n\nFor advanced scenarios, you can build search fields using SearchField directly. The following sample shows how to build search fields with SearchField.\n\n```java\n// Create a new search index structure that matches the properties of the Hotel class.\n List<SearchField> searchFieldList = new ArrayList<>();\n searchFieldList.add(new SearchField(\"hotelId\", SearchFieldDataType.STRING)\n .setKey(true)\n .setFilterable(true)\n .setSortable(true));\n\n searchFieldList.add(new SearchField(\"hotelName\", SearchFieldDataType.STRING)\n .setSearchable(true)\n .setFilterable(true)\n .setSortable(true));\n searchFieldList.add(new SearchField(\"description\", SearchFieldDataType.STRING)\n .setSearchable(true)\n .setAnalyzerName(LexicalAnalyzerName.EU_LUCENE));\n searchFieldList.add(new SearchField(\"tags\", SearchFieldDataType.collection(SearchFieldDataType.STRING))\n .setSearchable(true)\n .setFilterable(true)\n .setFacetable(true));\n searchFieldList.add(new SearchField(\"address\", SearchFieldDataType.COMPLEX)\n .setFields(new SearchField(\"streetAddress\", SearchFieldDataType.STRING).setSearchable(true),\n new SearchField(\"city\", SearchFieldDataType.STRING)\n .setSearchable(true)\n .setFilterable(true)\n .setFacetable(true)\n .setSortable(true),\n new SearchField(\"stateProvince\", SearchFieldDataType.STRING)\n .setSearchable(true)\n .setFilterable(true)\n .setFacetable(true)\n .setSortable(true),\n new SearchField(\"country\", SearchFieldDataType.STRING)\n .setSearchable(true)\n .setFilterable(true)\n .setFacetable(true)\n .setSortable(true),\n new SearchField(\"postalCode\", SearchFieldDataType.STRING)\n .setSearchable(true)\n .setFilterable(true)\n .setFacetable(true)\n .setSortable(true)\n ));\n\n // Prepare suggester.\n SearchSuggester suggester = new SearchSuggester(\"sg\", Collections.singletonList(\"hotelName\"));\n // Prepare SearchIndex with index name and search fields.\n SearchIndex index = new SearchIndex(\"hotels\").setFields(searchFieldList).setSuggesters(suggester);\n // Create an index\n searchIndexClient.createIndex(index);\n```\n\n#### Retrieving a specific document from your index ####\n\nIn addition to querying for documents using keywords and optional filters, you can retrieve a specific document from your index if you already know the key.\n\nThe following example retrieves a document using the document's key.\n\n```java\nHotel hotel = searchClient.getDocument(\"1\", Hotel.class);\n System.out.printf(\"Hotel ID: %s%n\", hotel.getHotelId());\n System.out.printf(\"Hotel Name: %s%n\", hotel.getHotelName());\n```\n\n#### Adding documents to your index ####\n\nYou can Upload, Merge, MergeOrUpload, and Delete multiple documents from an index in a single batched request. There are [a few special rules for merging][] to be aware of.\n\nThe following sample shows using a single batch request to perform a document upload and merge in a single request.\n\n```java\nIndexDocumentsBatch<Hotel> batch = new IndexDocumentsBatch<Hotel>();\n batch.addUploadActions(Collections.singletonList(\n new Hotel().setHotelId(\"783\").setHotelName(\"Upload Inn\")));\n batch.addMergeActions(Collections.singletonList(\n new Hotel().setHotelId(\"12\").setHotelName(\"Renovated Ranch\")));\n searchClient.indexDocuments(batch);\n```\n\n#### Async APIs ####\n\nThe examples so far have been using synchronous APIs. For asynchronous support and examples, please see our asynchronous clients:\n\n * SearchIndexAsyncClient\n * SearchIndexerAsyncClient\n * SearchAsyncClient\n\n### Authenticate in a National Cloud ###\n\nTo authenticate a [National Cloud][], you will need to make the following additions to your client configuration:\n\n * Set \\`AuthorityHost\\` in the credential potions or via the \\`AZURE\\_AUTHORITY\\_HOST\\` environment variable\n * Set the \\`audience\\` in SearchClientBuilder, SearchIndexClientBuilder, SearchIndexerClientBuilder\n\n```java\nSearchClient searchClient = new SearchClientBuilder()\n .endpoint(\"{endpoint}\")\n .credential(new DefaultAzureCredentialBuilder()\n .authorityHost(\"{national cloud endpoint}\")\n .build())\n .audience(SearchAudience.AZURE_PUBLIC_CLOUD) //set the audience of your cloud\n .buildClient();\n```\n\n### Troubleshooting ###\n\nSee our [troubleshooting guide][] for details on how to diagnose various failure scenarios.\n\n#### General ####\n\nWhen you interact with Azure AI Search using this Java client library, errors returned by the service correspond to the [same HTTP status codes returned for REST API requests.][] For example, the service will return a 404 error if you try to retrieve a document that doesn't exist in your index.\n\n#### Handling Search Error Response ####\n\nAny Search API operation that fails will throw an HttpResponseException with helpful [Status codes][same HTTP status codes returned for REST API requests.]. Many of these errors are recoverable.\n\n```java\ntry {\n Iterable<SearchResult> results = searchClient.search(\"hotel\");\n results.forEach(result -> {\n System.out.println(result.getDocument(Hotel.class).getHotelName());\n });\n } catch (HttpResponseException ex) {\n // The exception contains the HTTP status code and the detailed message\n // returned from the search service\n HttpResponse response = ex.getResponse();\n System.out.println(\"Status Code: \" + response.getStatusCode());\n System.out.println(\"Message: \" + ex.getMessage());\n }\n```\n\n\n[Azure AI Search]: https://learn.microsoft.com/azure/search/\n[An Azure subscription]: https://azure.microsoft.com/free/java/\n[An existing Azure AI Search service]: https://azure.microsoft.com/products/ai-services/ai-search/\n[Azure portal]: https://learn.microsoft.com/azure/search/search-create-service-portal\n[Azure Powershell]: https://learn.microsoft.com/azure/search/search-manage-powershell#create-or-delete-a-service\n[Azure CLI.]: https://learn.microsoft.com/cli/azure/search/service?view=azure-cli-latest#az-search-service-create\n[supported authenticating approaches]: https://learn.microsoft.com/azure/search/search-security-overview#authentication\n[Azure Portal.]: https://ms.portal.azure.com/\n[the documentation]: https://learn.microsoft.com/azure/search/search-security-api-keys?tabs=portal-use%2Cportal-find%2Cportal-query\n[Searching]: https://learn.microsoft.com/azure/search/search-lucene-query-architecture\n[rich queries]: https://learn.microsoft.com/azure/search/search-query-overview\n[powerful data shaping.]: https://learn.microsoft.com/azure/search/search-filters\n[Autocompleting]: https://learn.microsoft.com/rest/api/searchservice/autocomplete\n[Suggesting]: https://learn.microsoft.com/rest/api/searchservice/suggestions\n[Adding_ Updating or Deleting]: https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents\n[sample]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchExample.java\n[documentation]: https://learn.microsoft.com/azure/search/vector-search-overview\n[Hotel data set]: https://github.com/Azure-Samples/azure-search-sample-data\n[import into your own index from the Azure portal]: https://learn.microsoft.com/azure/search/search-get-started-portal#step-1---start-the-import-data-wizard-and-create-a-data-source\n[check out our Samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/README.md\n[a few special rules for merging]: https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents#document-actions\n[National Cloud]: https://learn.microsoft.com/azure/active-directory/develop/authentication-national-cloud\n[troubleshooting guide]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/TROUBLESHOOTING.md\n[same HTTP status codes returned for REST API requests.]: https://learn.microsoft.com/rest/api/searchservice/http-status-codes"
metadata: {}
package: "com.azure.search.documents"
artifact: com.azure:azure-search-documents:11.7.1