Search in sources :

Example 11 with Index

use of com.google.appengine.api.search.Index in project java-docs-samples by GoogleCloudPlatform.

the class SearchServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    PrintWriter out = resp.getWriter();
    Document doc = Document.newBuilder().setId("theOnlyPiano").addField(Field.newBuilder().setName("product").setText("piano")).addField(Field.newBuilder().setName("maker").setText("Yamaha")).addField(Field.newBuilder().setName("price").setNumber(4000)).build();
    try {
        Utils.indexADocument(SEARCH_INDEX, doc);
    } catch (InterruptedException e) {
    // ignore
    }
    // [START search_document]
    final int maxRetry = 3;
    int attempts = 0;
    int delay = 2;
    while (true) {
        try {
            String queryString = "product = piano AND price < 5000";
            Results<ScoredDocument> results = getIndex().search(queryString);
            // Iterate over the documents in the results
            for (ScoredDocument document : results) {
                // handle results
                out.print("maker: " + document.getOnlyField("maker").getText());
                out.println(", price: " + document.getOnlyField("price").getNumber());
            }
        } catch (SearchException e) {
            if (StatusCode.TRANSIENT_ERROR.equals(e.getOperationResult().getCode()) && ++attempts < maxRetry) {
                // retry
                try {
                    Thread.sleep(delay * 1000);
                } catch (InterruptedException e1) {
                // ignore
                }
                // easy exponential backoff
                delay *= 2;
                continue;
            } else {
                throw e;
            }
        }
        break;
    }
    // [END search_document]
    // We don't test the search result below, but we're fine if it runs without errors.
    out.println("Search performed");
    Index index = getIndex();
    // [START simple_search_1]
    index.search("rose water");
    // [END simple_search_1]
    // [START simple_search_2]
    index.search("1776-07-04");
    // [END simple_search_2]
    // [START simple_search_3]
    // search for documents with pianos that cost less than $5000
    index.search("product = piano AND price < 5000");
// [END simple_search_3]
}
Also used : ScoredDocument(com.google.appengine.api.search.ScoredDocument) SearchException(com.google.appengine.api.search.SearchException) Index(com.google.appengine.api.search.Index) Document(com.google.appengine.api.search.Document) ScoredDocument(com.google.appengine.api.search.ScoredDocument) PrintWriter(java.io.PrintWriter)

Example 12 with Index

use of com.google.appengine.api.search.Index in project java-docs-samples by GoogleCloudPlatform.

the class MultitenancyServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String namespace;
    PrintWriter out = resp.getWriter();
    out.println("Code Snippets -- not yet fully runnable as an app");
    // [START temp_namespace]
    // Set the namepace temporarily to "abc"
    String oldNamespace = NamespaceManager.get();
    NamespaceManager.set("abc");
    try {
    // ... perform operation using current namespace ...
    } finally {
        NamespaceManager.set(oldNamespace);
    }
    // [START per_user_namespace]
    if (com.google.appengine.api.NamespaceManager.get() == null) {
        // Assuming there is a logged in user.
        namespace = UserServiceFactory.getUserService().getCurrentUser().getUserId();
        NamespaceManager.set(namespace);
    }
    // [END per_user_namespace]
    String value = "something here";
    // [START ns_memcache]
    // Create a MemcacheService that uses the current namespace by
    // calling NamespaceManager.get() for every access.
    MemcacheService current = MemcacheServiceFactory.getMemcacheService();
    // stores value in namespace "abc"
    oldNamespace = NamespaceManager.get();
    NamespaceManager.set("abc");
    try {
        // stores value in namespace “abc”
        current.put("key", value);
    } finally {
        NamespaceManager.set(oldNamespace);
    }
    // [END ns_memcache]
    // [START specific_memcache]
    // Create a MemcacheService that uses the namespace "abc".
    MemcacheService explicit = MemcacheServiceFactory.getMemcacheService("abc");
    // stores value in namespace "abc"
    explicit.put("key", value);
    // [END specific_memcache]
    // [START searchns]
    // Set the current namespace to "aSpace"
    NamespaceManager.set("aSpace");
    // Create a SearchService with the namespace "aSpace"
    SearchService searchService = SearchServiceFactory.getSearchService();
    // Create an IndexSpec
    IndexSpec indexSpec = IndexSpec.newBuilder().setName("myIndex").build();
    // Create an Index with the namespace "aSpace"
    Index index = searchService.getIndex(indexSpec);
    // [END searchns]
    // [START searchns_2]
    // Create a SearchServiceConfig, specifying the namespace "anotherSpace"
    SearchServiceConfig config = SearchServiceConfig.newBuilder().setNamespace("anotherSpace").build();
    // Create a SearchService with the namespace "anotherSpace"
    searchService = SearchServiceFactory.getSearchService(config);
    // Create an IndexSpec
    indexSpec = IndexSpec.newBuilder().setName("myindex").build();
    // Create an Index with the namespace "anotherSpace"
    index = searchService.getIndex(indexSpec);
// [END searchns_2]
}
Also used : MemcacheService(com.google.appengine.api.memcache.MemcacheService) IndexSpec(com.google.appengine.api.search.IndexSpec) SearchService(com.google.appengine.api.search.SearchService) Index(com.google.appengine.api.search.Index) SearchServiceConfig(com.google.appengine.api.search.SearchServiceConfig) PrintWriter(java.io.PrintWriter)

Example 13 with Index

use of com.google.appengine.api.search.Index in project teammates by TEAMMATES.

the class SearchManager method putDocumentsWithRetry.

/**
 * Tries putting multiple documents, handling transient errors by retrying with exponential backoff.
 *
 * @throws PutException when only non-transient errors are encountered.
 * @throws MaximumRetriesExceededException with list of failed {@link Document}s as final data and
 *         final {@link OperationResult}'s message as final message, if operation fails after maximum retries.
 */
private static void putDocumentsWithRetry(String indexName, final List<Document> documents) throws PutException, MaximumRetriesExceededException {
    final Index index = getIndex(indexName);
    /*
         * The GAE Search API allows batch putting a List of Documents.
         * Results for each document are reported via a List of OperationResults.
         * We use RetryManager to retry putting a List of Documents, with each retry re-putting only
         * the documents that failed in the previous retry.
         * If we encounter one or more transient errors, we retry the operation.
         * If all results are non-transient errors, we give up and throw a PutException upwards.
         */
    RM.runUntilSuccessful(new RetryableTaskThrows<PutException>("Put documents") {

        private List<Document> documentsToPut = documents;

        private List<OperationResult> lastResults;

        private List<String> lastIds;

        @Override
        public void run() throws PutException {
            try {
                PutResponse response = index.put(documentsToPut);
                lastResults = response.getResults();
                lastIds = response.getIds();
            } catch (PutException e) {
                lastResults = e.getResults();
                lastIds = e.getIds();
            }
        }

        @Override
        public boolean isSuccessful() {
            boolean hasTransientError = false;
            List<Document> failedDocuments = new ArrayList<>();
            for (int i = 0; i < documentsToPut.size(); i++) {
                StatusCode code = lastResults.get(i).getCode();
                if (!StatusCode.OK.equals(code)) {
                    failedDocuments.add(documentsToPut.get(i));
                    if (StatusCode.TRANSIENT_ERROR.equals(code)) {
                        hasTransientError = true;
                    }
                }
            }
            // Update the list of documents to be put during the next retry
            documentsToPut = failedDocuments;
            // Update the final message and data to be shown if the task fails after maximum retries
            finalMessage = lastResults.get(0).getMessage();
            finalData = documentsToPut;
            if (documentsToPut.isEmpty()) {
                return true;
            } else if (hasTransientError) {
                // If there is at least one transient error, continue retrying
                return false;
            } else {
                // If all errors are non-transient, do not continue retrying
                throw new PutException(lastResults.get(0), lastResults, lastIds);
            }
        }
    });
}
Also used : Index(com.google.appengine.api.search.Index) OperationResult(com.google.appengine.api.search.OperationResult) Document(com.google.appengine.api.search.Document) ScoredDocument(com.google.appengine.api.search.ScoredDocument) PutResponse(com.google.appengine.api.search.PutResponse) StatusCode(com.google.appengine.api.search.StatusCode) PutException(com.google.appengine.api.search.PutException) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Index (com.google.appengine.api.search.Index)13 IndexSpec (com.google.appengine.api.search.IndexSpec)9 Document (com.google.appengine.api.search.Document)5 PrintWriter (java.io.PrintWriter)4 PutException (com.google.appengine.api.search.PutException)3 ScoredDocument (com.google.appengine.api.search.ScoredDocument)3 OperationResult (com.google.appengine.api.search.OperationResult)2 PutResponse (com.google.appengine.api.search.PutResponse)2 SearchException (com.google.appengine.api.search.SearchException)2 MemcacheService (com.google.appengine.api.memcache.MemcacheService)1 FieldType (com.google.appengine.api.search.Field.FieldType)1 Query (com.google.appengine.api.search.Query)1 QueryOptions (com.google.appengine.api.search.QueryOptions)1 Schema (com.google.appengine.api.search.Schema)1 SearchService (com.google.appengine.api.search.SearchService)1 SearchServiceConfig (com.google.appengine.api.search.SearchServiceConfig)1 SortOptions (com.google.appengine.api.search.SortOptions)1 StatusCode (com.google.appengine.api.search.StatusCode)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1