com.google.appengine.api.search.SearchServiceFactory Java Examples

The following examples show how to use com.google.appengine.api.search.SearchServiceFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SearchServiceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearchServiceConfig() throws ExecutionException, InterruptedException {
    String indexName = "put-index";
    String docId = "testPutDocs";
    searchService = SearchServiceFactory.getSearchService(SearchServiceConfig.newBuilder().setDeadline(10.).build());

    Index index = createIndex(indexName, docId);

    GetIndexesRequest request = GetIndexesRequest.newBuilder()
            .setIndexNamePrefix(indexName)
            .build();
    GetResponse<Index> response = searchService.getIndexes(request);
    List<Index> listIndexes = response.getResults();

    for (Index oneIndex : listIndexes) {
        Results<ScoredDocument> res = oneIndex.search("");

        Iterator<ScoredDocument> it = res.iterator();
        assertEquals(docId + "1", it.next().getId());
        assertEquals(docId + "2", it.next().getId());
        sync();
    }
}
 
Example #2
Source File: Utils.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Put a given document into an index with the given indexName.
 *
 * @param indexName The name of the index.
 * @param document A document to add.
 * @throws InterruptedException When Thread.sleep is interrupted.
 */
// [START putting_document_with_retry]
public static void indexADocument(String indexName, Document document)
    throws InterruptedException {
  IndexSpec indexSpec = IndexSpec.newBuilder().setName(indexName).build();
  Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);

  final int maxRetry = 3;
  int attempts = 0;
  int delay = 2;
  while (true) {
    try {
      index.put(document);
    } catch (PutException e) {
      if (StatusCode.TRANSIENT_ERROR.equals(e.getOperationResult().getCode())
          && ++attempts < maxRetry) { // retrying
        Thread.sleep(delay * 1000);
        delay *= 2; // easy exponential backoff
        continue;
      } else {
        throw e; // otherwise throw
      }
    }
    break;
  }
}
 
Example #3
Source File: UtilsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void indexADocument_successfullyInvoked() throws Exception {
  String id = "test";
  Document doc =
      Document.newBuilder()
          .setId(id)
          .addField(Field.newBuilder().setName("f").setText("v"))
          .build();
  Utils.indexADocument(INDEX, doc);
  // get the document by id
  IndexSpec indexSpec = IndexSpec.newBuilder().setName(INDEX).build();
  Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
  Document fetched = index.get(id);
  assertWithMessage("A value of the fetched document")
      .that(fetched.getOnlyField("f").getText())
      .isEqualTo("v");
}
 
Example #4
Source File: IndexServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  PrintWriter out = resp.getWriter();
  Document document =
      Document.newBuilder()
          .setId("AZ125")
          .addField(Field.newBuilder().setName("myField").setText("myValue"))
          .build();
  try {
    Utils.indexADocument(INDEX, document);
  } catch (InterruptedException e) {
    out.println("Interrupted");
    return;
  }
  out.println("Indexed a new document.");
  // [START get_document]
  IndexSpec indexSpec = IndexSpec.newBuilder().setName(INDEX).build();
  Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);

  // Fetch a single document by its  doc_id
  Document doc = index.get("AZ125");

  // Fetch a range of documents by their doc_ids
  GetResponse<Document> docs =
      index.getRange(GetRequest.newBuilder().setStartId("AZ125").setLimit(100).build());
  // [END get_document]
  out.println("myField: " + docs.getResults().get(0).getOnlyField("myField").getText());
}
 
Example #5
Source File: SchemaServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  PrintWriter out = resp.getWriter();
  Document doc =
      Document.newBuilder()
          .setId("theOnlyCar")
          .addField(Field.newBuilder().setName("maker").setText("Toyota"))
          .addField(Field.newBuilder().setName("price").setNumber(300000))
          .addField(Field.newBuilder().setName("color").setText("lightblue"))
          .addField(Field.newBuilder().setName("model").setText("Prius"))
          .build();
  try {
    Utils.indexADocument(SEARCH_INDEX, doc);
  } catch (InterruptedException e) {
    // ignore
  }
  // [START list_schema]
  GetResponse<Index> response =
      SearchServiceFactory.getSearchService()
          .getIndexes(GetIndexesRequest.newBuilder().setSchemaFetched(true).build());

  // List out elements of each Schema
  for (Index index : response) {
    Schema schema = index.getSchema();
    for (String fieldName : schema.getFieldNames()) {
      List<FieldType> typesForField = schema.getFieldTypes(fieldName);
      // Just printing out the field names and types
      for (FieldType type : typesForField) {
        out.println(index.getName() + ":" + fieldName + ":" + type.name());
      }
    }
  }
  // [END list_schema]
}
 
Example #6
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamespaceWithBug() throws InterruptedException, ParseException {
    String ns = "ns-indextest";
    String indexName = "ns-index";
    int docCount = 5;
    NamespaceManager.set(ns);
    SearchService searchService2 = SearchServiceFactory.getSearchService();
    Index index = searchService2.getIndex(IndexSpec.newBuilder()
            .setName(indexName)
            .build());
    delDocs(index);
    addDocs(index, docCount);

    GetIndexesRequest request = GetIndexesRequest.newBuilder()
        .setIndexNamePrefix(indexName)
        .setOffset(0)
        .setNamespace(ns)
        .setLimit(10)
        .build();
    assertEquals(ns, request.getNamespace());
    GetResponse<Index> response = searchService2.getIndexes(request);
    List<Index> listIndexes = response.getResults();
    for (Index oneIndex : listIndexes) {
        assertEquals(ns, listIndexes.get(0).getNamespace());
        assertEquals(indexName, listIndexes.get(0).getName());
        verifyDocCount(oneIndex, docCount);
    }
    assertEquals(ns, searchService2.getNamespace());
    NamespaceManager.set("");
}
 
Example #7
Source File: SearchServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void initIndexes() {
  SearchService search = SearchServiceFactory.getSearchService();
  IndexSpec.Builder spec = IndexSpec.newBuilder();

  for (int i = 0; i < 25; i++) {
    String name = String.format("index%s", i);
    spec.setName(name);
    addDocuments(search.getIndex(spec), name, i == 0 ? 25 : 1);
  }
  search = SearchServiceFactory.getSearchService("ns");
  spec.setName("<b>");
  addDocuments(search.getIndex(spec), "other", 1);
}
 
Example #8
Source File: SearchManager.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private static Index getIndex(String indexName) {
    Map<String, Index> indicesTable = getIndicesTable();
    Index index = indicesTable.get(indexName);
    if (index == null) {
        IndexSpec indexSpec = IndexSpec.newBuilder().setName(indexName).build();
        index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
        indicesTable.put(indexName, index);
    }
    return index;
}
 
Example #9
Source File: SearchOptionServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private Results<ScoredDocument> doSearch() {
  String indexName = SEARCH_INDEX;
  // [START search_with_options]
  try {
    // Build the SortOptions with 2 sort keys
    SortOptions sortOptions =
        SortOptions.newBuilder()
            .addSortExpression(
                SortExpression.newBuilder()
                    .setExpression("price")
                    .setDirection(SortExpression.SortDirection.DESCENDING)
                    .setDefaultValueNumeric(0))
            .addSortExpression(
                SortExpression.newBuilder()
                    .setExpression("brand")
                    .setDirection(SortExpression.SortDirection.DESCENDING)
                    .setDefaultValue(""))
            .setLimit(1000)
            .build();

    // Build the QueryOptions
    QueryOptions options =
        QueryOptions.newBuilder()
            .setLimit(25)
            .setFieldsToReturn("model", "price", "description")
            .setSortOptions(sortOptions)
            .build();

    // A query string
    String queryString = "product: coffee roaster AND price < 500";

    //  Build the Query and run the search
    Query query = Query.newBuilder().setOptions(options).build(queryString);
    IndexSpec indexSpec = IndexSpec.newBuilder().setName(indexName).build();
    Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
    Results<ScoredDocument> result = index.search(query);
    return result;
  } catch (SearchException e) {
    // handle exception...
  }
  // [END search_with_options]
  return null;
}
 
Example #10
Source File: PlacesHelper.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 4 votes vote down vote up
static Index getIndex() {
  IndexSpec indexSpec = IndexSpec.newBuilder().setName(INDEX_NAME).build();
  return SearchServiceFactory.getSearchService().getIndex(indexSpec);
}
 
Example #11
Source File: SearchTestBase.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    searchService = SearchServiceFactory.getSearchService();
}
 
Example #12
Source File: GallerySearchIndex.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
/**
 * @return the search index
 */
private Index getIndex() {
  IndexSpec indexSpec = IndexSpec.newBuilder().setName(GALLERYINDEX).build();
  Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
  return index;
}
 
Example #13
Source File: SearchOptionServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private Index getIndex() {
  IndexSpec indexSpec = IndexSpec.newBuilder().setName(SEARCH_INDEX).build();
  Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
  return index;
}
 
Example #14
Source File: SearchServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private Index getIndex() {
  IndexSpec indexSpec = IndexSpec.newBuilder().setName(SEARCH_INDEX).build();
  Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
  return index;
}
 
Example #15
Source File: DeleteServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private Index getIndex() {
  IndexSpec indexSpec = IndexSpec.newBuilder().setName(SEARCH_INDEX).build();
  Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
  return index;
}
 
Example #16
Source File: MultitenancyServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@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);
  }
  // [END temp_namespace]

  // [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 {
    current.put("key", value); // stores value in namespace “abc”
  } finally {
    NamespaceManager.set(oldNamespace);
  }
  // [END ns_memcache]

  // [START specific_memcache]
  // Create a MemcacheService that uses the namespace "abc".
  MemcacheService explicit = MemcacheServiceFactory.getMemcacheService("abc");
  explicit.put("key", value); // stores value in namespace "abc"
  // [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]

}
 
Example #17
Source File: PlacesHelper.java    From MobileShoppingAssistant-sample with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the Places index in the datastore.
 * @return The index to use to search places in the datastore.
 */
public static Index getIndex() {
    IndexSpec indexSpec = IndexSpec.newBuilder().setName(INDEX_NAME)
            .build();
    return SearchServiceFactory.getSearchService().getIndex(indexSpec);
}