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]
}
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]
}
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);
}
}
});
}
Aggregations