Search Document Add

事前準備

    • Indexを作っておく

    • フィールドを定義しておく

コード

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': [" // + "{" // フィールドと同じ構造 + "'@search.action': 'upload'" + "," // <-コマンドに相当 + "'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()); } }}

結果

{"@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}]}