Search in sources :

Example 11 with QueryResponse

use of com.ibm.watson.discovery.v1.model.QueryResponse in project java-sdk by watson-developer-cloud.

the class Discovery method query.

/**
 * Query documents.
 *
 * See the [Discovery service documentation](https://console.bluemix.net/docs/services/discovery/using.html) for more
 * details.
 *
 * @param queryOptions the {@link QueryOptions} containing the options for the call
 * @return a {@link ServiceCall} with a response type of {@link QueryResponse}
 */
public ServiceCall<QueryResponse> query(QueryOptions queryOptions) {
    Validator.notNull(queryOptions, "queryOptions cannot be null");
    String[] pathSegments = { "v1/environments", "collections", "query" };
    String[] pathParameters = { queryOptions.environmentId(), queryOptions.collectionId() };
    RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments, pathParameters));
    builder.query(VERSION, versionDate);
    if (queryOptions.filter() != null) {
        builder.query("filter", queryOptions.filter());
    }
    if (queryOptions.query() != null) {
        builder.query("query", queryOptions.query());
    }
    if (queryOptions.naturalLanguageQuery() != null) {
        builder.query("natural_language_query", queryOptions.naturalLanguageQuery());
    }
    if (queryOptions.passages() != null) {
        builder.query("passages", String.valueOf(queryOptions.passages()));
    }
    if (queryOptions.aggregation() != null) {
        builder.query("aggregation", queryOptions.aggregation());
    }
    if (queryOptions.count() != null) {
        builder.query("count", String.valueOf(queryOptions.count()));
    }
    if (queryOptions.returnFields() != null) {
        builder.query("return", RequestUtils.join(queryOptions.returnFields(), ","));
    }
    if (queryOptions.offset() != null) {
        builder.query("offset", String.valueOf(queryOptions.offset()));
    }
    if (queryOptions.sort() != null) {
        builder.query("sort", RequestUtils.join(queryOptions.sort(), ","));
    }
    if (queryOptions.highlight() != null) {
        builder.query("highlight", String.valueOf(queryOptions.highlight()));
    }
    if (queryOptions.passagesFields() != null) {
        builder.query("passages.fields", RequestUtils.join(queryOptions.passagesFields(), ","));
    }
    if (queryOptions.passagesCount() != null) {
        builder.query("passages.count", String.valueOf(queryOptions.passagesCount()));
    }
    if (queryOptions.passagesCharacters() != null) {
        builder.query("passages.characters", String.valueOf(queryOptions.passagesCharacters()));
    }
    if (queryOptions.deduplicate() != null) {
        builder.query("deduplicate", String.valueOf(queryOptions.deduplicate()));
    }
    if (queryOptions.deduplicateField() != null) {
        builder.query("deduplicate.field", queryOptions.deduplicateField());
    }
    if (queryOptions.similar() != null) {
        builder.query("similar", String.valueOf(queryOptions.similar()));
    }
    if (queryOptions.similarDocumentIds() != null) {
        builder.query("similar.document_ids", RequestUtils.join(queryOptions.similarDocumentIds(), ","));
    }
    if (queryOptions.similarFields() != null) {
        builder.query("similar.fields", RequestUtils.join(queryOptions.similarFields(), ","));
    }
    return createServiceCall(builder.build(), ResponseConverterUtils.getObject(QueryResponse.class));
}
Also used : RequestBuilder(com.ibm.watson.developer_cloud.http.RequestBuilder) QueryResponse(com.ibm.watson.developer_cloud.discovery.v1.model.QueryResponse)

Example 12 with QueryResponse

use of com.ibm.watson.discovery.v1.model.QueryResponse 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();
}
Also used : DocumentAccepted(com.ibm.watson.discovery.v2.model.DocumentAccepted) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) QueryOptions(com.ibm.watson.discovery.v2.model.QueryOptions) FileInputStream(java.io.FileInputStream) QueryResult(com.ibm.watson.discovery.v2.model.QueryResult) AddDocumentOptions(com.ibm.watson.discovery.v2.model.AddDocumentOptions) QueryResponse(com.ibm.watson.discovery.v2.model.QueryResponse) BearerTokenAuthenticator(com.ibm.cloud.sdk.core.security.BearerTokenAuthenticator) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) BearerTokenAuthenticator(com.ibm.cloud.sdk.core.security.BearerTokenAuthenticator) DeleteDocumentOptions(com.ibm.watson.discovery.v2.model.DeleteDocumentOptions)

Example 13 with QueryResponse

use of com.ibm.watson.discovery.v1.model.QueryResponse in project java-sdk by watson-developer-cloud.

the class DiscoveryServiceTest method queryIsSuccessful.

/**
 * Query is successful.
 *
 * @throws InterruptedException the interrupted exception
 */
// Query tests
@Test
public void queryIsSuccessful() throws InterruptedException {
    server.enqueue(jsonResponse(queryResp));
    QueryOptions.Builder queryBuilder = new QueryOptions.Builder(environmentId, collectionId);
    queryBuilder.count(5L);
    queryBuilder.offset(5L);
    String fieldNames = "field";
    queryBuilder.xReturn(fieldNames);
    queryBuilder.query("field" + Operator.CONTAINS + 1);
    queryBuilder.filter("field" + Operator.CONTAINS + 1);
    queryBuilder.similar(true);
    String similarDocumentIds = "doc1, doc2";
    queryBuilder.similarDocumentIds(similarDocumentIds);
    String similarFields = "field1, field2";
    queryBuilder.similarFields(similarFields);
    queryBuilder.xWatsonLoggingOptOut(true);
    queryBuilder.bias("bias");
    QueryResponse response = discoveryService.query(queryBuilder.build()).execute().getResult();
    RecordedRequest request = server.takeRequest();
    assertEquals(Q1_PATH, request.getPath());
    assertEquals(POST, request.getMethod());
    assertEquals(GsonSingleton.getGson().toJsonTree(queryResp), GsonSingleton.getGson().toJsonTree(response));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) LogQueryResponse(com.ibm.watson.discovery.v1.model.LogQueryResponse) QueryResponse(com.ibm.watson.discovery.v1.model.QueryResponse) FederatedQueryOptions(com.ibm.watson.discovery.v1.model.FederatedQueryOptions) GetMetricsQueryOptions(com.ibm.watson.discovery.v1.model.GetMetricsQueryOptions) QueryOptions(com.ibm.watson.discovery.v1.model.QueryOptions) WatsonServiceUnitTest(com.ibm.watson.common.WatsonServiceUnitTest)

Example 14 with QueryResponse

use of com.ibm.watson.discovery.v1.model.QueryResponse in project java-sdk by watson-developer-cloud.

the class Discovery method federatedQuery.

/**
 * Query multiple collections.
 *
 * <p>By using this method, you can construct long queries that search multiple collection. For
 * details, see the [Discovery
 * documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts).
 *
 * @param federatedQueryOptions the {@link FederatedQueryOptions} containing the options for the
 *     call
 * @return a {@link ServiceCall} with a result of type {@link QueryResponse}
 */
public ServiceCall<QueryResponse> federatedQuery(FederatedQueryOptions federatedQueryOptions) {
    com.ibm.cloud.sdk.core.util.Validator.notNull(federatedQueryOptions, "federatedQueryOptions cannot be null");
    Map<String, String> pathParamsMap = new HashMap<String, String>();
    pathParamsMap.put("environment_id", federatedQueryOptions.environmentId());
    RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/v1/environments/{environment_id}/query", pathParamsMap));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("discovery", "v1", "federatedQuery");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    if (federatedQueryOptions.xWatsonLoggingOptOut() != null) {
        builder.header("X-Watson-Logging-Opt-Out", federatedQueryOptions.xWatsonLoggingOptOut());
    }
    builder.query("version", String.valueOf(this.version));
    final JsonObject contentJson = new JsonObject();
    contentJson.addProperty("collection_ids", federatedQueryOptions.collectionIds());
    if (federatedQueryOptions.filter() != null) {
        contentJson.addProperty("filter", federatedQueryOptions.filter());
    }
    if (federatedQueryOptions.query() != null) {
        contentJson.addProperty("query", federatedQueryOptions.query());
    }
    if (federatedQueryOptions.naturalLanguageQuery() != null) {
        contentJson.addProperty("natural_language_query", federatedQueryOptions.naturalLanguageQuery());
    }
    if (federatedQueryOptions.passages() != null) {
        contentJson.addProperty("passages", federatedQueryOptions.passages());
    }
    if (federatedQueryOptions.aggregation() != null) {
        contentJson.addProperty("aggregation", federatedQueryOptions.aggregation());
    }
    if (federatedQueryOptions.count() != null) {
        contentJson.addProperty("count", federatedQueryOptions.count());
    }
    if (federatedQueryOptions.xReturn() != null) {
        contentJson.addProperty("return", federatedQueryOptions.xReturn());
    }
    if (federatedQueryOptions.offset() != null) {
        contentJson.addProperty("offset", federatedQueryOptions.offset());
    }
    if (federatedQueryOptions.sort() != null) {
        contentJson.addProperty("sort", federatedQueryOptions.sort());
    }
    if (federatedQueryOptions.highlight() != null) {
        contentJson.addProperty("highlight", federatedQueryOptions.highlight());
    }
    if (federatedQueryOptions.passagesFields() != null) {
        contentJson.addProperty("passages.fields", federatedQueryOptions.passagesFields());
    }
    if (federatedQueryOptions.passagesCount() != null) {
        contentJson.addProperty("passages.count", federatedQueryOptions.passagesCount());
    }
    if (federatedQueryOptions.passagesCharacters() != null) {
        contentJson.addProperty("passages.characters", federatedQueryOptions.passagesCharacters());
    }
    if (federatedQueryOptions.deduplicate() != null) {
        contentJson.addProperty("deduplicate", federatedQueryOptions.deduplicate());
    }
    if (federatedQueryOptions.deduplicateField() != null) {
        contentJson.addProperty("deduplicate.field", federatedQueryOptions.deduplicateField());
    }
    if (federatedQueryOptions.similar() != null) {
        contentJson.addProperty("similar", federatedQueryOptions.similar());
    }
    if (federatedQueryOptions.similarDocumentIds() != null) {
        contentJson.addProperty("similar.document_ids", federatedQueryOptions.similarDocumentIds());
    }
    if (federatedQueryOptions.similarFields() != null) {
        contentJson.addProperty("similar.fields", federatedQueryOptions.similarFields());
    }
    if (federatedQueryOptions.bias() != null) {
        contentJson.addProperty("bias", federatedQueryOptions.bias());
    }
    builder.bodyJson(contentJson);
    ResponseConverter<QueryResponse> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<QueryResponse>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) HashMap(java.util.HashMap) LogQueryResponse(com.ibm.watson.discovery.v1.model.LogQueryResponse) QueryResponse(com.ibm.watson.discovery.v1.model.QueryResponse) JsonObject(com.google.gson.JsonObject)

Example 15 with QueryResponse

use of com.ibm.watson.discovery.v1.model.QueryResponse 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);
}
Also used : RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) HashMap(java.util.HashMap) QueryResponse(com.ibm.watson.discovery.v2.model.QueryResponse) JsonObject(com.google.gson.JsonObject)

Aggregations

QueryResponse (com.ibm.watson.developer_cloud.discovery.v1.model.QueryResponse)23 Test (org.junit.Test)21 QueryOptions (com.ibm.watson.developer_cloud.discovery.v1.model.QueryOptions)20 WatsonServiceTest (com.ibm.watson.developer_cloud.WatsonServiceTest)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)8 QueryResponse (com.ibm.watson.discovery.v1.model.QueryResponse)7 LogQueryResponse (com.ibm.watson.discovery.v1.model.LogQueryResponse)6 JsonObject (com.google.gson.JsonObject)5 Collection (com.ibm.watson.developer_cloud.discovery.v1.model.Collection)5 FileInputStream (java.io.FileInputStream)5 InputStream (java.io.InputStream)5 Calculation (com.ibm.watson.developer_cloud.discovery.v1.model.Calculation)4 FederatedQueryOptions (com.ibm.watson.discovery.v1.model.FederatedQueryOptions)4 QueryOptions (com.ibm.watson.discovery.v1.model.QueryOptions)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 RequestBuilder (com.ibm.cloud.sdk.core.http.RequestBuilder)3 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)3 DocumentAccepted (com.ibm.watson.developer_cloud.discovery.v1.model.DocumentAccepted)3 FederatedQueryOptions (com.ibm.watson.developer_cloud.discovery.v1.model.FederatedQueryOptions)3 GetMetricsQueryOptions (com.ibm.watson.discovery.v1.model.GetMetricsQueryOptions)3