Add Document to Azure Search Service (Java)

Advance preparation

code


package hello.azure;

import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class AzureSearchDocumentAdd {

	public static void main(String[] args) throws Exception {

		// @see
		// https://docs.microsoft.com/ja-jp/rest/api/searchservice/create-index
		// https://docs.microsoft.com/ja-jp/rest/api/searchservice/addupdate-or-delete-documents

		// POST https://[service name].search.windows.net/indexes/[index name]/docs/index?api-version=[api-version]
		// Content-Type: application/json
		// api-key: [admin key]

		// from console
		String adminKey = "xxx";

		HttpClient httpclient = HttpClients.createDefault();

		String serviceName = "yyy";
		String indexName = "zzz";

		String dateValue = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")).format(new Date());

		String json = "{" //
				+ "'value': [" //
				+ "{" //Same structure as the field
				+ "'@search.action': 'upload'" + "," // <-Equivalent to a command
				+ "'id': '001'" + "," //
				+ "'description': 'Hello'" + "," //
				+ "'date': '" + dateValue + "'" + ", " //
				+ "'item1': 'aaa'" + ", " //
				+ "'item2': 100" + ", " //
				+ "'item3':[{'item3_1':'bbb'}]" //
				+ "}" //
				+ "]" //
				+ "}" //
		; // 

		try {
			URIBuilder builder = new URIBuilder("https://" + serviceName + ".search.windows.net/indexes/" + indexName
					+ "/docs/index?api-version=2019-05-06"); //

			URI uri = builder.build();
			HttpPost request = new HttpPost(uri);
			request.setHeader("Content-Type", "application/json");
			request.setHeader("api-key", adminKey);

			// Request body
			StringEntity reqEntity = new StringEntity(json);
			request.setEntity(reqEntity);

			HttpResponse response = httpclient.execute(request);
			HttpEntity entity = response.getEntity();

			int responseCode = response.getStatusLine().getStatusCode();
			if (responseCode == 200) {
				System.err.println(
						"200 is returned for a successful response, meaning that all items have been stored durably and will start to be indexed.");
			} else if (responseCode == 201) {
				System.err.println("201 (for newly uploaded documents)");
			} else {
				System.err.println(responseCode);
			}
			if (entity != null) {
				System.out.println(EntityUtils.toString(entity));
			}

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

}


result

{
"@odata.context":"https://yyy.search.windows.net/indexes('zzz')/$metadata#Collection(Microsoft.Azure.Search.V2019_05_06.IndexResult)",
"value":[
 {"key":"001","status":true,"errorMessage":null,"statusCode":200}
]
}

Verification

You can also try queries against the index from the admin console.

Recommended Posts

Add Document to Azure Search Service (Java)
Add watermark to Java to PDF document
[Java] Add WordArt to Word document
Add multi-letter watermark to Java Word
Add / remove watermark to Java PowerPoint
Java (add2)
Java (add)
Introduction to algorithms with java --Search (depth-first search)
How to print a Java Word document
Add footnotes to Word documents in Java
Creating Java Web Applications to Azure Web Apps
Add SameSite attribute to cookie in Java
Introduction to algorithms with java --Search (breadth-first search)
Upsert from Java SDK to Azure Cosmos DB
[Java] Add quotes only to specific CSV columns
Introduction to algorithms with java --Search (bit full search)
Deploy Java web app to Azure with maven
Method to search
Try Azure Service Fabric (Java) on Mac-Local Environment
Java upload and download notes to Azure storage
[Java] Introduction to Java
[Java] Article to add validation with Spring Boot 2.3.1.
Introduction to java
Java 11 document summary
Select * from Java SDK to Azure Cosmos DB
PKIX path building failed: Add SSL certificate to java
Use Maven to add your favorite Java library to your environment.
Search by POST request with Azure Search + Java Apache HttpClient
Get Azure App Service for Java Configuration with System.getEnv ()
Android-Upload image files to Azure Blob Storage in Java
[Java] I tried to implement Yahoo API product search
[Java] [XML signature] Add prefix and ID to Signature tag
Add files to jar files
Changes from Java 8 to Java 11
Sum from Java_1 to 100
Java compressed PDF document
[Java] Connect to MySQL
Azure functions in java
Kotlin's improvements to Java
[Note] Java: String search
[Java] Initialize, add, get
From Java to Ruby !!
Introduction to java command
java: Add date [Note]
How to use SAS tokens for Azure Event hubs (Java)
20190803_Java & k8s on Azure The story of going to the festival
Append text to BlobItem in Azure BlobStorage SDK Java V8