use of com.ibm.watson.discovery.v2.model.QueryOptions in project java-sdk by watson-developer-cloud.
the class DiscoveryServiceIT method addDocumentWithMetadataIsSuccessful.
@Ignore
@SuppressWarnings("deprecation")
@Test
public void addDocumentWithMetadataIsSuccessful() {
Collection collection = createTestCollection();
String collectionId = collection.getCollectionId();
String myDocumentJson = "{\"field\":\"value\"}";
InputStream documentStream = new ByteArrayInputStream(myDocumentJson.getBytes());
JsonObject myMetadata = new JsonObject();
myMetadata.add("foo", new JsonPrimitive("bar"));
AddDocumentOptions.Builder builder = new AddDocumentOptions.Builder(environmentId, collectionId);
builder.file(documentStream).fileContentType(HttpMediaType.APPLICATION_JSON);
builder.filename("test_file");
builder.metadata(myMetadata.toString());
DocumentAccepted createResponse = discovery.addDocument(builder.build()).execute();
WaitFor.Condition documentAccepted = new WaitForDocumentAccepted(environmentId, collectionId, createResponse.getDocumentId());
WaitFor.waitFor(documentAccepted, 5, TimeUnit.SECONDS, 500);
QueryOptions queryOptions = new QueryOptions.Builder(environmentId, collectionId).build();
QueryResponse queryResponse = discovery.query(queryOptions).execute();
assertTrue(queryResponse.getResults().get(0).getMetadata() != null);
}
use of com.ibm.watson.discovery.v2.model.QueryOptions in project java-sdk by watson-developer-cloud.
the class DiscoveryV2Example method main.
public static void main(String[] args) throws IOException {
Authenticator authenticator = new BearerTokenAuthenticator("{bearer_token}");
Discovery service = new Discovery("2019-11-22", authenticator);
service.setServiceUrl("{url}");
// This example assumes you have a project and collection set up which can accept documents.
// Paste those
// IDs below.
String projectId = "";
String collectionId = "";
// Add a new document to our collection. Fill in the file path with the file you want to send.
InputStream file = new FileInputStream("");
AddDocumentOptions addDocumentOptions = new AddDocumentOptions.Builder().projectId(projectId).collectionId(collectionId).file(file).filename("example-file").build();
DocumentAccepted addResponse = service.addDocument(addDocumentOptions).execute().getResult();
String documentId = addResponse.getDocumentId();
// Query your collection with the new document inside.
QueryOptions queryOptions = new QueryOptions.Builder().projectId(projectId).addCollectionIds(collectionId).naturalLanguageQuery(// Feel free to replace this to query something different.
"Watson").build();
QueryResponse queryResponse = service.query(queryOptions).execute().getResult();
System.out.println(queryResponse.getMatchingResults() + " results were returned by the query!");
// See if the added document got returned by the query.
for (QueryResult result : queryResponse.getResults()) {
if (result.getDocumentId().equals(documentId)) {
System.out.println("Our new document matched the query!");
}
}
// Delete our uploaded document from the collection.
DeleteDocumentOptions deleteDocumentOptions = new DeleteDocumentOptions.Builder().projectId(projectId).collectionId(collectionId).documentId(documentId).build();
service.deleteDocument(deleteDocumentOptions).execute();
}
use of com.ibm.watson.discovery.v2.model.QueryOptions in project java-sdk by watson-developer-cloud.
the class Discovery method query.
/**
* Query a project.
*
* <p>By using this method, you can construct queries. For details, see the [Discovery
* documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts).
* The default query parameters are defined by the settings for this project, see the [Discovery
* documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-project-defaults)
* for an overview of the standard default settings, and see [the Projects API
* documentation](#create-project) for details about how to set custom default query settings.
*
* @param queryOptions the {@link QueryOptions} containing the options for the call
* @return a {@link ServiceCall} with a result of type {@link QueryResponse}
*/
public ServiceCall<QueryResponse> query(QueryOptions queryOptions) {
com.ibm.cloud.sdk.core.util.Validator.notNull(queryOptions, "queryOptions cannot be null");
Map<String, String> pathParamsMap = new HashMap<String, String>();
pathParamsMap.put("project_id", queryOptions.projectId());
RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/v2/projects/{project_id}/query", pathParamsMap));
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("discovery", "v2", "query");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
builder.query("version", String.valueOf(this.version));
final JsonObject contentJson = new JsonObject();
if (queryOptions.collectionIds() != null) {
contentJson.add("collection_ids", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(queryOptions.collectionIds()));
}
if (queryOptions.filter() != null) {
contentJson.addProperty("filter", queryOptions.filter());
}
if (queryOptions.query() != null) {
contentJson.addProperty("query", queryOptions.query());
}
if (queryOptions.naturalLanguageQuery() != null) {
contentJson.addProperty("natural_language_query", queryOptions.naturalLanguageQuery());
}
if (queryOptions.aggregation() != null) {
contentJson.addProperty("aggregation", queryOptions.aggregation());
}
if (queryOptions.count() != null) {
contentJson.addProperty("count", queryOptions.count());
}
if (queryOptions.xReturn() != null) {
contentJson.add("return", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(queryOptions.xReturn()));
}
if (queryOptions.offset() != null) {
contentJson.addProperty("offset", queryOptions.offset());
}
if (queryOptions.sort() != null) {
contentJson.addProperty("sort", queryOptions.sort());
}
if (queryOptions.highlight() != null) {
contentJson.addProperty("highlight", queryOptions.highlight());
}
if (queryOptions.spellingSuggestions() != null) {
contentJson.addProperty("spelling_suggestions", queryOptions.spellingSuggestions());
}
if (queryOptions.tableResults() != null) {
contentJson.add("table_results", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(queryOptions.tableResults()));
}
if (queryOptions.suggestedRefinements() != null) {
contentJson.add("suggested_refinements", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(queryOptions.suggestedRefinements()));
}
if (queryOptions.passages() != null) {
contentJson.add("passages", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(queryOptions.passages()));
}
builder.bodyJson(contentJson);
ResponseConverter<QueryResponse> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<QueryResponse>() {
}.getType());
return createServiceCall(builder.build(), responseConverter);
}
use of com.ibm.watson.discovery.v2.model.QueryOptions in project java-sdk by watson-developer-cloud.
the class DiscoveryServiceIT method updateDocumentWithMetadataIsSuccessful.
@Test
@Ignore("Pending implementation of 'processing' after document update")
public void updateDocumentWithMetadataIsSuccessful() {
Collection collection = createTestCollection();
String collectionId = collection.getCollectionId();
DocumentAccepted documentAccepted = createTestDocument("test_document", collectionId);
String myDocumentJson = "{\"field\":\"value2\"}";
InputStream documentStream = new ByteArrayInputStream(myDocumentJson.getBytes());
JsonObject myMetadata = new JsonObject();
myMetadata.add("foo", new JsonPrimitive("bar"));
UpdateDocumentOptions.Builder updateBuilder = new UpdateDocumentOptions.Builder(environmentId, collectionId, documentAccepted.getDocumentId());
updateBuilder.file(documentStream).fileContentType(HttpMediaType.APPLICATION_JSON);
updateBuilder.metadata(myMetadata.toString());
DocumentAccepted updateResponse = discovery.updateDocument(updateBuilder.build()).execute();
WaitFor.Condition waitForDocumentAccepted = new WaitForDocumentAccepted(environmentId, collectionId, updateResponse.getDocumentId());
WaitFor.waitFor(waitForDocumentAccepted, 5, TimeUnit.SECONDS, 500);
QueryOptions queryOptions = new QueryOptions.Builder(environmentId, collectionId).build();
QueryResponse queryResponse = discovery.query(queryOptions).execute();
assertTrue(queryResponse.getResults().get(0).getMetadata() != null);
}
use of com.ibm.watson.discovery.v2.model.QueryOptions in project java-sdk by watson-developer-cloud.
the class DiscoveryTest method testQueryWOptions.
@Test
public void testQueryWOptions() throws Throwable {
// Schedule some responses.
String mockResponseBody = "{\"matching_results\": 15, \"results\": [{\"document_id\": \"documentId\", \"metadata\": {\"mapKey\": \"anyValue\"}, \"result_metadata\": {\"document_retrieval_source\": \"search\", \"collection_id\": \"collectionId\", \"confidence\": 10}, \"document_passages\": [{\"passage_text\": \"passageText\", \"start_offset\": 11, \"end_offset\": 9, \"field\": \"field\", \"confidence\": 0, \"answers\": [{\"answer_text\": \"answerText\", \"start_offset\": 11, \"end_offset\": 9, \"confidence\": 0}]}]}], \"aggregations\": [{\"type\": \"filter\", \"match\": \"match\", \"matching_results\": 15}], \"retrieval_details\": {\"document_retrieval_strategy\": \"untrained\"}, \"suggested_query\": \"suggestedQuery\", \"suggested_refinements\": [{\"text\": \"text\"}], \"table_results\": [{\"table_id\": \"tableId\", \"source_document_id\": \"sourceDocumentId\", \"collection_id\": \"collectionId\", \"table_html\": \"tableHtml\", \"table_html_offset\": 15, \"table\": {\"location\": {\"begin\": 5, \"end\": 3}, \"text\": \"text\", \"section_title\": {\"text\": \"text\", \"location\": {\"begin\": 5, \"end\": 3}}, \"title\": {\"text\": \"text\", \"location\": {\"begin\": 5, \"end\": 3}}, \"table_headers\": [{\"cell_id\": \"cellId\", \"location\": {\"mapKey\": \"anyValue\"}, \"text\": \"text\", \"row_index_begin\": 13, \"row_index_end\": 11, \"column_index_begin\": 16, \"column_index_end\": 14}], \"row_headers\": [{\"cell_id\": \"cellId\", \"location\": {\"begin\": 5, \"end\": 3}, \"text\": \"text\", \"text_normalized\": \"textNormalized\", \"row_index_begin\": 13, \"row_index_end\": 11, \"column_index_begin\": 16, \"column_index_end\": 14}], \"column_headers\": [{\"cell_id\": \"cellId\", \"location\": {\"mapKey\": \"anyValue\"}, \"text\": \"text\", \"text_normalized\": \"textNormalized\", \"row_index_begin\": 13, \"row_index_end\": 11, \"column_index_begin\": 16, \"column_index_end\": 14}], \"key_value_pairs\": [{\"key\": {\"cell_id\": \"cellId\", \"location\": {\"begin\": 5, \"end\": 3}, \"text\": \"text\"}, \"value\": [{\"cell_id\": \"cellId\", \"location\": {\"begin\": 5, \"end\": 3}, \"text\": \"text\"}]}], \"body_cells\": [{\"cell_id\": \"cellId\", \"location\": {\"begin\": 5, \"end\": 3}, \"text\": \"text\", \"row_index_begin\": 13, \"row_index_end\": 11, \"column_index_begin\": 16, \"column_index_end\": 14, \"row_header_ids\": [{\"id\": \"id\"}], \"row_header_texts\": [{\"text\": \"text\"}], \"row_header_texts_normalized\": [{\"text_normalized\": \"textNormalized\"}], \"column_header_ids\": [{\"id\": \"id\"}], \"column_header_texts\": [{\"text\": \"text\"}], \"column_header_texts_normalized\": [{\"text_normalized\": \"textNormalized\"}], \"attributes\": [{\"type\": \"type\", \"text\": \"text\", \"location\": {\"begin\": 5, \"end\": 3}}]}], \"contexts\": [{\"text\": \"text\", \"location\": {\"begin\": 5, \"end\": 3}}]}}], \"passages\": [{\"passage_text\": \"passageText\", \"passage_score\": 12, \"document_id\": \"documentId\", \"collection_id\": \"collectionId\", \"start_offset\": 11, \"end_offset\": 9, \"field\": \"field\", \"confidence\": 0, \"answers\": [{\"answer_text\": \"answerText\", \"start_offset\": 11, \"end_offset\": 9, \"confidence\": 0}]}]}";
String queryPath = "/v2/projects/testString/query";
server.enqueue(new MockResponse().setHeader("Content-type", "application/json").setResponseCode(200).setBody(mockResponseBody));
constructClientService();
// Construct an instance of the QueryLargeTableResults model
QueryLargeTableResults queryLargeTableResultsModel = new QueryLargeTableResults.Builder().enabled(true).count(Long.valueOf("26")).build();
// Construct an instance of the QueryLargeSuggestedRefinements model
QueryLargeSuggestedRefinements queryLargeSuggestedRefinementsModel = new QueryLargeSuggestedRefinements.Builder().enabled(true).count(Long.valueOf("1")).build();
// Construct an instance of the QueryLargePassages model
QueryLargePassages queryLargePassagesModel = new QueryLargePassages.Builder().enabled(true).perDocument(true).maxPerDocument(Long.valueOf("26")).fields(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).count(Long.valueOf("400")).characters(Long.valueOf("50")).findAnswers(false).maxAnswersPerPassage(Long.valueOf("26")).build();
// Construct an instance of the QueryOptions model
QueryOptions queryOptionsModel = new QueryOptions.Builder().projectId("testString").collectionIds(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).filter("testString").query("testString").naturalLanguageQuery("testString").aggregation("testString").count(Long.valueOf("26")).xReturn(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))).offset(Long.valueOf("26")).sort("testString").highlight(true).spellingSuggestions(true).tableResults(queryLargeTableResultsModel).suggestedRefinements(queryLargeSuggestedRefinementsModel).passages(queryLargePassagesModel).build();
// Invoke operation with valid options model (positive test)
Response<QueryResponse> response = discoveryService.query(queryOptionsModel).execute();
assertNotNull(response);
QueryResponse responseObj = response.getResult();
assertNotNull(responseObj);
// Verify the contents of the request
RecordedRequest request = server.takeRequest();
assertNotNull(request);
assertEquals(request.getMethod(), "POST");
// Check query
Map<String, String> query = TestUtilities.parseQueryString(request);
assertNotNull(query);
// Get query params
assertEquals(query.get("version"), "testString");
// Check request path
String parsedPath = TestUtilities.parseReqPath(request);
assertEquals(parsedPath, queryPath);
}
Aggregations