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

The following examples show how to use com.google.appengine.api.search.Document. 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: PlacesHelper.java    From MobileShoppingAssistant-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a new Place document to insert in the Places index.
 * @param placeId      the identifier of the place in the database.
 * @param placeName    the name of the place.
 * @param placeAddress the address of the place.
 * @param location     the GPS location of the place, as a GeoPt.
 * @return the Place document created.
 */
public static Document buildDocument(
        final Long placeId, final String placeName,
        final String placeAddress, final GeoPt location) {
    GeoPoint geoPoint = new GeoPoint(location.getLatitude(),
            location.getLongitude());

    Document.Builder builder = Document.newBuilder()
            .addField(Field.newBuilder().setName("id")
                    .setText(placeId.toString()))
            .addField(Field.newBuilder().setName("name").setText(placeName))
            .addField(Field.newBuilder().setName("address")
                    .setText(placeAddress))
            .addField(Field.newBuilder().setName("place_location")
                    .setGeoPoint(geoPoint));

    // geo-location doesn't work under dev_server, so let's add another
    // field to use for retrieving documents
    if (environment.value() == Development) {
        builder.addField(Field.newBuilder().setName("value").setNumber(1));
    }

    return builder.build();
}
 
Example #2
Source File: PlacesHelper.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 6 votes vote down vote up
static Document buildDocument(
    String placeId, String placeName, String placeAddress, GeoPt location) {
  GeoPoint geoPoint = new GeoPoint(location.getLatitude(), location.getLongitude());

  Document.Builder builder = Document.newBuilder()
      .addField(Field.newBuilder().setName("id").setText(placeId))
      .addField(Field.newBuilder().setName("name").setText(placeName))
      .addField(Field.newBuilder().setName("address").setText(placeAddress))
      .addField(Field.newBuilder().setName("place_location").setGeoPoint(geoPoint));

  // geo-location doesn't work under dev_server, so let's add another
  // field to use for retrieving documents
  if (environment.value() == Development) {
    builder.addField(Field.newBuilder().setName("value").setNumber(1));
  }

  Document place = builder.build();

  return place;
}
 
Example #3
Source File: SearchServiceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private Index createIndex(String indexName, String docId) {
    Index index = searchService.getIndex(IndexSpec.newBuilder()
            .setName(indexName)
            .build());

    Field field = Field.newBuilder().setName("subject").setText("put(Document.Builder)").build();
    Document.Builder docBuilder = Document.newBuilder()
            .setId(docId + "1")
            .addField(field);
    index.put(docBuilder);

    field = Field.newBuilder().setName("subject").setText("put(Document)").build();
    Document document = Document.newBuilder()
            .setId(docId + "2")
            .addField(field).build();
    index.put(document);
    return index;
}
 
Example #4
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private Index createIndex(String indexName, String docId) {
    Index index = searchService.getIndex(IndexSpec.newBuilder()
            .setName(indexName)
            .build());

    Field field = Field.newBuilder().setName("subject").setText("put(Document.Builder)").build();
    Document.Builder docBuilder = Document.newBuilder()
            .setId(docId + "1")
            .addField(field);
    index.put(docBuilder);

    field = Field.newBuilder().setName("subject").setText("put(Document)").build();
    Document document = Document.newBuilder()
            .setId(docId + "2")
            .addField(field).build();
    index.put(document);
    return index;
}
 
Example #5
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutGetRangeAsyncBuilder() throws InterruptedException, ExecutionException {
    String indexName = "put-index";
    String docId = "testPutDocs";
    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) {
        Future<GetResponse<Document>> futurDocs = oneIndex.getRangeAsync(GetRequest.newBuilder().setStartId(docId + "1").setLimit(10));
        sync();
        assertEquals(futurDocs.get().getResults().size(), 2);
    }
}
 
Example #6
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutGetRangeAsyncGetResponse() throws InterruptedException, ExecutionException {
    String indexName = "put-index";
    String docId = "testPutDocs";
    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) {
        Future<GetResponse<Document>> futurDocs = oneIndex.getRangeAsync(GetRequest.newBuilder().setStartId(docId + "1").setLimit(10).build());
        sync();
        assertEquals(futurDocs.get().getResults().size(), 2);
    }
}
 
Example #7
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutGetRangeBuilder() throws InterruptedException {
    String indexName = "put-index";
    String docId = "testPutDocs";
    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) {
        GetResponse<Document> docs = oneIndex.getRange(GetRequest.newBuilder().setStartId(docId + "1").setLimit(10));
        sync();
        assertEquals(docs.getResults().size(), 2);
    }
}
 
Example #8
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutGetRangeGetRequest() throws InterruptedException {
    String indexName = "put-index";
    String docId = "testPutDocs";
    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) {
        GetResponse<Document> docs = oneIndex.getRange(GetRequest.newBuilder().setStartId(docId + "1").setLimit(10).build());
        sync();
        assertEquals(docs.getResults().size(), 2);
    }
}
 
Example #9
Source File: InstructorSearchDocument.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected Document toDocument() {

    String delim = ",";

    // produce searchableText for this instructor document:
    // contains courseId, courseName, instructorName, instructorEmail, instructorGoogleId, instructorRole, displayedName
    String searchableText = instructor.courseId + delim
                            + (course == null ? "" : course.getName()) + delim
                            + instructor.name + delim
                            + instructor.email + delim
                            + (instructor.googleId == null ? "" : instructor.googleId) + delim
                            + instructor.role + delim
                            + instructor.displayedName;

    return Document.newBuilder()
            // searchableText is used to match the query string
            .addField(Field.newBuilder().setName(Const.SearchDocumentField.SEARCHABLE_TEXT)
                                        .setText(searchableText))
            .setId(StringHelper.encrypt(instructor.key))
            .build();
}
 
Example #10
Source File: StudentSearchDocument.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Document toDocument() {

    String delim = ",";

    // produce searchableText for this student document:
    // it contains courseId, courseName, studentEmail, studentName studentTeam and studentSection
    String searchableText = student.course + delim
                            + (course == null ? "" : course.getName()) + delim
                            + student.email + delim
                            + student.name + delim
                            + student.team + delim
                            + student.section;

    return Document.newBuilder()
            // this is used to filter documents visible to certain instructor
            .addField(Field.newBuilder().setName(Const.SearchDocumentField.COURSE_ID)
                                        .setText(student.course))
            // searchableText and createdDate are used to match the query string
            .addField(Field.newBuilder().setName(Const.SearchDocumentField.SEARCHABLE_TEXT)
                                        .setText(searchableText))
            .setId(student.key)
            .build();
}
 
Example #11
Source File: GallerySearchIndex.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * index gallery app into search index
 * @param app galleryapp
 */
public void indexApp (GalleryApp app) {
  // take the title, description, and the user name and index it
  // need to build up a string with all meta data
  String indexWords = app.getTitle()+" "+app.getDescription() + " " + app.getDeveloperName();
  // now create the doc
  Document doc = Document.newBuilder()
    .setId(String.valueOf(app.getGalleryAppId()))
    .addField(Field.newBuilder().setName("content").setText(indexWords))
    .build();

  Index index = getIndex();

  try {
    index.put(doc);
  } catch (PutException e) {
    if (StatusCode.TRANSIENT_ERROR.equals(e.getOperationResult().getCode())) {
        // retry putting the document
    }
  }
}
 
Example #12
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 #13
Source File: MaintenanceTasksServlet.java    From MobileShoppingAssistant-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Cleans the index of places from all entries.
 */
private void removeAllDocumentsFromIndex() {
    Index index = PlacesHelper.getIndex();
    // As the request will only return up to 1000 documents,
    // we need to loop until there are no more documents in the index.
    // We batch delete 1000 documents per iteration.
    final int numberOfDocuments = 1000;
    while (true) {
        GetRequest request = GetRequest.newBuilder()
                .setReturningIdsOnly(true)
                .build();

        ArrayList<String> documentIds = new ArrayList<>(numberOfDocuments);
        GetResponse<Document> response = index.getRange(request);
        for (Document document : response.getResults()) {
            documentIds.add(document.getId());
        }

        if (documentIds.size() == 0) {
            break;
        }

        index.delete(documentIds);
    }
}
 
Example #14
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 #15
Source File: DocumentServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Code snippet for creating a Document.
 *
 * @return Document Created document.
 */
public Document createDocument() {
  // [START create_document]
  User currentUser = UserServiceFactory.getUserService().getCurrentUser();
  String userEmail = currentUser == null ? "" : currentUser.getEmail();
  String userDomain = currentUser == null ? "" : currentUser.getAuthDomain();
  String myDocId = "PA6-5000";
  Document doc =
      Document.newBuilder()
          // Setting the document identifer is optional.
          // If omitted, the search service will create an identifier.
          .setId(myDocId)
          .addField(Field.newBuilder().setName("content").setText("the rain in spain"))
          .addField(Field.newBuilder().setName("email").setText(userEmail))
          .addField(Field.newBuilder().setName("domain").setAtom(userDomain))
          .addField(Field.newBuilder().setName("published").setDate(new Date()))
          .build();
  // [END create_document]
  return doc;
}
 
Example #16
Source File: DocumentServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  PrintWriter out = resp.getWriter();
  Document document =
      Document.newBuilder()
          .addField(Field.newBuilder().setName("coverLetter").setText("CoverLetter"))
          .addField(Field.newBuilder().setName("resume").setHTML("<html></html>"))
          .addField(Field.newBuilder().setName("fullName").setAtom("Foo Bar"))
          .addField(Field.newBuilder().setName("submissionDate").setDate(new Date()))
          .build();
  // [START access_document]
  String coverLetter = document.getOnlyField("coverLetter").getText();
  String resume = document.getOnlyField("resume").getHTML();
  String fullName = document.getOnlyField("fullName").getAtom();
  Date submissionDate = document.getOnlyField("submissionDate").getDate();
  // [END access_document]
  out.println("coverLetter: " + coverLetter);
  out.println("resume: " + resume);
  out.println("fullName: " + fullName);
  out.println("submissionDate: " + submissionDate.toString());
}
 
Example #17
Source File: SearchOptionServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  // Put one document to avoid an error
  Document document =
      Document.newBuilder()
          .setId("theOnlyCoffeeRoaster")
          .addField(Field.newBuilder().setName("price").setNumber(200))
          .addField(Field.newBuilder().setName("model").setText("TZ4000"))
          .addField(Field.newBuilder().setName("brand").setText("MyBrand"))
          .addField(Field.newBuilder().setName("product").setText("coffee roaster"))
          .addField(
              Field.newBuilder().setName("description").setText("A coffee bean roaster at home"))
          .build();
  try {
    Utils.indexADocument(SEARCH_INDEX, document);
  } catch (InterruptedException e) {
    // ignore
  }
  PrintWriter out = resp.getWriter();
  Results<ScoredDocument> result = doSearch();
  for (ScoredDocument doc : result.getResults()) {
    out.println(doc.toString());
  }
}
 
Example #18
Source File: DocumentServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void createDocument_withoutSignedIn() throws Exception {
  helper.setEnvIsLoggedIn(false);
  Document doc = servletUnderTest.createDocument();
  assertWithMessage("content")
      .that(doc.getOnlyField("content").getText())
      .contains("the rain in spain");
  assertWithMessage("email").that(doc.getOnlyField("email").getText()).isEmpty();
}
 
Example #19
Source File: MaintenanceTasksServlet.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
private void removeAllDocumentsFromIndex() {
  Index index = PlacesHelper.getIndex();

  GetRequest request = GetRequest.newBuilder().setReturningIdsOnly(true).build();

  GetResponse<Document> response = index.getRange(request);
  for (Document document : response.getResults()) {
    index.delete(document.getId());
  }
}
 
Example #20
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private void verifyDocCount(Index index, int docCount) {
    if (docCount == -1) {
        String name = index.getName();
        docCount = Integer.valueOf(name.substring(name.length() - 1));
    }
    List<Document> docList = index.getRange(GetRequest.newBuilder().build()).getResults();
    assertEquals(docCount, docList.size());
}
 
Example #21
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 #22
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAsyncDocument() {
    String indexName = "put-index";
    String docId = "testPutDocs";

    Index index = searchService.getIndex(IndexSpec.newBuilder()
            .setName(indexName)
            .build());

    Field field = Field.newBuilder().setName("subject").setText("put(Document)").build();
    Document document = Document.newBuilder()
            .setId(docId + "1")
            .addField(field).build();

    Future<PutResponse> resp = index.putAsync(document);

    while (!resp.isDone()) {
        if (resp.isCancelled()) {
            break;
        }
    }

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

    for (Index oneIndex : listIndexes) {
        Field retField = oneIndex.get(docId + "1").getOnlyField("subject");
        sync();
        assertEquals("put(Document)", retField.getText());
    }
}
 
Example #23
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAsyncBuilder() {
    String indexName = "put-index";
    String docId = "testPutDocs";

    Index index = searchService.getIndex(IndexSpec.newBuilder()
            .setName(indexName)
            .build());

    Field field = Field.newBuilder().setName("subject").setText("put(Document.Builder)").build();
    Document.Builder docBuilder = Document.newBuilder()
            .setId(docId + "1")
            .addField(field);

    index.putAsync(docBuilder);

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

    for (Index oneIndex : listIndexes) {
        Field retField = oneIndex.get(docId + "1").getOnlyField("subject");
        sync();
        assertEquals("put(Document.Builder)", retField.getText());
    }
}
 
Example #24
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 #25
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutDeleteAsyncDocsByString() throws InterruptedException {
    String indexName = "put-index";
    String docId = "testPutDocs";
    List<String> docIdList = new ArrayList<>();
    Index index = searchService.getIndex(IndexSpec.newBuilder()
            .setName(indexName)
            .build());

    Field field = Field.newBuilder().setName("subject").setText("put(Document.Builder)").build();
    Document.Builder docBuilder = Document.newBuilder()
            .setId(docId + "1")
            .addField(field);
    index.put(docBuilder);
    docIdList.add(docId + "1");

    field = Field.newBuilder().setName("subject").setText("put(Document)").build();
    Document document = Document.newBuilder()
            .setId(docId + "2")
            .addField(field).build();
    index.put(document);
    docIdList.add(docId + "1");

    GetIndexesRequest request = GetIndexesRequest.newBuilder()
            .setIndexNamePrefix(indexName)
            .build();
    GetResponse<Index> response = searchService.getIndexes(request);
    List<Index> listIndexes = response.getResults();
    for (Index oneIndex : listIndexes) {
        Field retField = oneIndex.get(docId + "1").getOnlyField("subject");
        assertEquals("put(Document.Builder)", retField.getText());
        retField = oneIndex.get(docId + "2").getOnlyField("subject");
        assertEquals("put(Document)", retField.getText());
        oneIndex.deleteAsync(docIdList.get(0));
        sync();
        assertNull(oneIndex.get(docIdList.get(0)));
    }
}
 
Example #26
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutDeleteDocs() throws InterruptedException {
    String indexName = "put-index";
    String docId = "testPutDocs";
    List<String> docIdList = new ArrayList<>();
    Index index = searchService.getIndex(IndexSpec.newBuilder()
        .setName(indexName)
        .build());

    Field field = Field.newBuilder().setName("subject").setText("put(Document.Builder)").build();
    Document.Builder docBuilder = Document.newBuilder()
        .setId(docId + "1")
        .addField(field);
    index.put(docBuilder);
    docIdList.add(docId + "1");

    field = Field.newBuilder().setName("subject").setText("put(Document)").build();
    Document document = Document.newBuilder()
        .setId(docId + "2")
        .addField(field).build();
    index.put(document);
    docIdList.add(docId + "1");

    GetIndexesRequest request = GetIndexesRequest.newBuilder()
        .setIndexNamePrefix(indexName)
        .build();
    GetResponse<Index> response = searchService.getIndexes(request);
    List<Index> listIndexes = response.getResults();
    for (Index oneIndex : listIndexes) {
        Field retField = oneIndex.get(docId + "1").getOnlyField("subject");
        assertEquals("put(Document.Builder)", retField.getText());
        retField = oneIndex.get(docId + "2").getOnlyField("subject");
        assertEquals("put(Document)", retField.getText());
        oneIndex.delete(docIdList.get(0));
        sync();
        assertNull(oneIndex.get(docIdList.get(0)));
    }
}
 
Example #27
Source File: DocumentTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateDocument() throws Exception {
    String indexName = "test-doc";
    Index index = searchService.getIndex(IndexSpec.newBuilder().setName(indexName));
    delDocs(index);
    Builder docBuilder = Document.newBuilder().setId("tck").setLocale(Locale.FRENCH).setRank(8);
    docBuilder.addField(Field.newBuilder().setName("field1").setText("text field"));
    docBuilder.addField(Field.newBuilder().setName("field1").setNumber(987));
    docBuilder.addField(Field.newBuilder().setName("field2").setNumber(123));
    docBuilder.addField(Field.newBuilder().setName("field3").setDate(new Date()));
    index.put(docBuilder.build());
    sync();

    Results<ScoredDocument> result = searchDocs(index, "", 0);
    assertEquals(1, result.getNumberReturned());
    ScoredDocument retDoc = result.iterator().next();
    assertEquals("tck", retDoc.getId());
    assertEquals(Locale.FRENCH, retDoc.getLocale());
    assertEquals(8, retDoc.getRank());
    assertEquals(2, retDoc.getFieldCount("field1"));
    assertEquals(1, retDoc.getFieldCount("field3"));
    assertEquals(3, retDoc.getFieldNames().size());

    Iterator<Field> fields = retDoc.getFields().iterator();
    int count = 0;
    for ( ; fields.hasNext() ; ++count ) {
        fields.next();
    }
    assertEquals(4, count);

    fields = retDoc.getFields("field1").iterator();
    count = 0;
    for ( ; fields.hasNext() ; ++count ) {
        fields.next();
    }
    assertEquals(2, count);

    Field field = retDoc.getOnlyField("field2");
    assertEquals(FieldType.NUMBER, field.getType());
}
 
Example #28
Source File: SearchTestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected void addDocs(Index index, int docCount) throws ParseException, InterruptedException {
    if (searchDocs(index, "", 0).getNumberFound() == 0) {
        List<Document> documents = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        DateFormat dfDate = new SimpleDateFormat("yyyy,M,d");
        for (int i = 0; i < docCount; i++) {
            Builder docBuilder = Document.newBuilder();
            // two text field with different locale
            docBuilder.addField(Field.newBuilder().setName("textfield").setText("text with num " + i));
            Field field = Field.newBuilder().setName("textfield").setText("C'est la vie " + i).setLocale(Locale.FRENCH).build();
            docBuilder.addField(field);
            docBuilder.addField(Field.newBuilder().setName("numfield").setNumber(i));
            String dateVal = "" + cal.get(Calendar.YEAR) + ",";
            dateVal += cal.get(Calendar.MONTH) + ",";
            int day = cal.get(Calendar.DATE) + i;
            dateVal += day;
            docBuilder.addField(Field.newBuilder().setName("datefield").setDate(dfDate.parse(dateVal)));
            docBuilder.addField(Field.newBuilder().setName("htmlfield").setHTML("<B>html</B> " + i));
            docBuilder.addField(Field.newBuilder().setName("atomfield").setAtom("atom" + i + ".com"));
            GeoPoint geoPoint = new GeoPoint((double) i, (double) (100 + i));
            docBuilder.addField(Field.newBuilder().setName("geofield").setGeoPoint(geoPoint));
            // two field in same name and with different field type
            docBuilder.addField(Field.newBuilder().setName("mixfield").setText("text and number mix field"));
            docBuilder.addField(Field.newBuilder().setName("mixfield").setNumber(987));
            docBuilder.setId("selfid" + i);
            // only doc(id="selfid0") has "cn" locale, others have "en" locale
            if (i == 0) {
                docBuilder.setLocale(new Locale("cn"));
            } else {
                docBuilder.setLocale(new Locale("en"));
            }
            documents.add(docBuilder.build());
        }
        index.put(documents);
        sync();
    }
}
 
Example #29
Source File: SearchServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void addDocument(Index index, String docid) {
  Document.Builder builder = Document.newBuilder();
  builder.setId(docid);
  builder.setRank(docid.hashCode());

  Field.Builder field = Field.newBuilder();
  field.setName("title");
  field.setText(String.format("Title: title%%<%s>", docid));
  builder.addField(field);

  field = Field.newBuilder();
  field.setName("body");
  field.setHTML(String.format("<h3>body of %s, some string</h3>", docid));
  builder.addField(field);

  field = Field.newBuilder();
  field.setName("atom");
  field.setAtom(String.format("atom%% <%s>", docid));
  builder.addField(field);

  field = Field.newBuilder();
  field.setName("number");
  field.setNumber(docid.hashCode() % 4096);
  builder.addField(field);

  field = Field.newBuilder();
  field.setName("date");
  field.setDate(new Date(2011 - 1900, 11 - 1, (docid.hashCode() % 30) + 1));
  builder.addField(field);

  index.put(builder.build());
}
 
Example #30
Source File: DocumentServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void createDocument_withSignedInUser() throws Exception {
  String email = "[email protected]";
  String authDomain = "example.com";
  helper.setEnvEmail(email);
  helper.setEnvAuthDomain(authDomain);
  helper.setEnvIsLoggedIn(true);
  Document doc = servletUnderTest.createDocument();
  assertWithMessage("content")
      .that(doc.getOnlyField("content").getText())
      .contains("the rain in spain");
  assertWithMessage("email").that(doc.getOnlyField("email").getText()).isEqualTo(email);
}