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

The following examples show how to use com.google.appengine.api.search.Field. 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: SearchServiceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testLocale() {
    Results<ScoredDocument> result = searchDocs(index, "", 0);
    for (ScoredDocument doc : result) {
        String id = doc.getId();
        if (id.endsWith("0")) {
            assertEquals(new Locale("cn"), doc.getLocale());
        } else {
            assertEquals(new Locale("en"), doc.getLocale());
        }

        boolean found = false;
        for (Field textField : doc.getFields("textfield")) {
            Locale locale = textField.getLocale();
            if ((locale != null) && locale.equals(Locale.FRENCH)) {
                found = true;
            }
        }
        assertTrue(found);
    }
}
 
Example #5
Source File: SearchServiceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void  testGetField() {
    String namelist = "geofield; textfield; numfield; atomfield; datefield; htmlfield; mixfield";
    Results<ScoredDocument> result = searchDocs(index, "", 0);
    for (ScoredDocument doc : result) {
        assertEquals(2, doc.getFieldCount("textfield"));
        String id = doc.getId();
        assertNotNull(id);
        if (id.endsWith("0")) {
            assertEquals(new Locale("cn"), doc.getLocale());
        } else {
            assertEquals(new Locale("en"), doc.getLocale());
        }

        for (String name : doc.getFieldNames()) {
            assertTrue(namelist.contains(name));
        }

        Iterator<Field> fields = doc.getFields().iterator();
        int count = 0;
        for ( ; fields.hasNext() ; ++count ) {
            fields.next();
        }
        assertEquals(9, count);
    }
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: SearchServiceTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testSortOptions() {
    for (SortExpression.SortDirection direction : SortExpression.SortDirection.values()) {
        SortExpression sortExpression = SortExpression.newBuilder()
            .setExpression("numfield")
            .setDirection(direction)
            .setDefaultValueNumeric(9999)
            .build();
        SortOptions sortOptions = SortOptions.newBuilder()
            .addSortExpression(sortExpression)
            .build();
        QueryOptions options = QueryOptions.newBuilder()
            .setFieldsToReturn("numfield", "datefield")
            .setSortOptions(sortOptions)
            .build();
        Query.Builder queryBuilder = Query.newBuilder().setOptions(options);
        Results<ScoredDocument> results = index.search(queryBuilder.build(""));

        double pre = -9999;
        if (direction.equals(SortExpression.SortDirection.DESCENDING)) {
            pre = 9999;
        }
        for (ScoredDocument doc : results) {
            assertEquals(2, doc.getFieldNames().size());
            for (Field numField : doc.getFields("numfield")) {
                if (direction.equals(SortExpression.SortDirection.DESCENDING)) {
                    assertTrue(pre > numField.getNumber());
                } else {
                    assertTrue(pre < numField.getNumber());
                }
                pre = numField.getNumber();
            }
        }
    }
}
 
Example #17
Source File: SearchServiceTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void  testGetOnlyField() {
    Results<ScoredDocument> result = searchDocs(index, "text with num 0", 0);
    for (ScoredDocument doc : result) {
        @SuppressWarnings("UnusedDeclaration")
        Field field = doc.getOnlyField("textfield");
    }
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
Source File: FieldTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidNull() {
    Field field = Field.newBuilder().setName("textfield").setText(null).build();
    assertEquals(null, field.getText());
    field = Field.newBuilder().setName("numberfield").setHTML(null).build();
    assertEquals(null, field.getNumber());
    field = Field.newBuilder().setName("htmlfield").setHTML(null).build();
    assertEquals(null, field.getHTML());
    field = Field.newBuilder().setName("atomfield").setAtom(null).build();
    assertEquals(null, field.getAtom());
}
 
Example #23
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 #24
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 #25
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 #26
Source File: FieldTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testInvalidGeoNull() {
    Field.newBuilder().setName("geofield").setGeoPoint(null);
}
 
Example #27
Source File: FieldTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testInvalidDateNull() {
    Field.newBuilder().setName("datefield").setDate(null);
}
 
Example #28
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Test
public void testPutAsyncIterable() {
    String indexName = "put-index";
    String docId = "testPutDocs";

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

    List<Document> documents = new ArrayList<>();
    Field field = Field.newBuilder().setName("subject").setText("put(Document)").build();
    Document document1 = Document.newBuilder()
            .setId(docId + "1")
            .addField(field).build();
    field = Field.newBuilder().setName("subject").setText("put(Document)").build();
    Document document2 = Document.newBuilder()
            .setId(docId + "2")
            .addField(field).build();

    documents.add(document1);
    documents.add(document2);

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

    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");
        assertEquals("put(Document)", retField.getText());
        retField = oneIndex.get(docId + "2").getOnlyField("subject");
        assertEquals("put(Document)", retField.getText());
        sync();
    }
}
 
Example #29
Source File: FieldTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Test
public void testDocFields() throws Exception {
    String indexName = "test-doc-fields";
    Index index = searchService.getIndex(IndexSpec.newBuilder().setName(indexName));
    delDocs(index);

    Builder docBuilder = Document.newBuilder();
    Field field = Field.newBuilder().setName("textfield").setText("text field").build();
    docBuilder.addField(field);
    field = Field.newBuilder().setName("numberfield").setNumber(123).build();
    docBuilder.addField(field);
    Date now = new Date();
    field = Field.newBuilder().setName("datefield").setDate(now).build();
    docBuilder.addField(field);
    field = Field.newBuilder().setName("htmlfield").setHTML("<html>html field</html>").build();
    docBuilder.addField(field);
    User currentUser = new User("[email protected]", "appenginetest.com");
    field = Field.newBuilder().setName("atomfield").setAtom(currentUser.getAuthDomain()).build();
    docBuilder.addField(field);
    GeoPoint geoPoint = new GeoPoint((double) -10, 10.000001);
    field = Field.newBuilder().setName("geofield").setGeoPoint(geoPoint).build();
    docBuilder.addField(field);
    index.put(docBuilder);
    sync();

    Results<ScoredDocument> result = searchDocs(index, "", 0);
    assertEquals(1, result.getNumberReturned());
    ScoredDocument doc = result.iterator().next();
    Field retField = doc.getOnlyField("textfield");
    assertEquals(FieldType.TEXT, retField.getType());
    assertEquals("textfield", retField.getName());
    assertEquals("text field", retField.getText());

    retField = doc.getOnlyField("numberfield");
    assertEquals(FieldType.NUMBER, retField.getType());
    assertEquals(new Double("123"), retField.getNumber());

    retField = doc.getOnlyField("datefield");
    assertEquals(FieldType.DATE, retField.getType());
    assertEquals(now, retField.getDate());

    retField = doc.getOnlyField("htmlfield");
    assertEquals(FieldType.HTML, retField.getType());
    assertEquals("<html>html field</html>", retField.getHTML());

    retField = doc.getOnlyField("atomfield");
    assertEquals(FieldType.ATOM, retField.getType());
    assertEquals(currentUser.getAuthDomain(), retField.getAtom());

    retField = doc.getOnlyField("geofield");
    assertEquals(FieldType.GEO_POINT, retField.getType());
    assertEquals(-10, retField.getGeoPoint().getLatitude(), 0);
    assertEquals(10.000001, retField.getGeoPoint().getLongitude(), 0.000000);
}
 
Example #30
Source File: DocumentTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testMultipleDateField() {
    Builder docBuilder = Document.newBuilder();
    docBuilder.addField(Field.newBuilder().setName("datefield").setDate(new Date()));
    docBuilder.addField(Field.newBuilder().setName("datefield").setDate(new Date()));
}