Example usage for com.liferay.portal.kernel.search Field Field

List of usage examples for com.liferay.portal.kernel.search Field Field

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.search Field Field.

Prototype

public Field(String name, String[] values) 

Source Link

Usage

From source file:com.liferay.document.library.internal.search.SearchResultUtilDLFileEntryTest.java

License:Open Source License

@Test
public void testDLFileEntryWithBrokenIndexer() throws Exception {
    Mockito.when(_dlAppLocalService.getFileEntry(SearchTestUtil.ENTRY_CLASS_PK)).thenReturn(_fileEntry);

    Mockito.doThrow(new IllegalArgumentException()).when(_indexer).getSummary((Document) Matchers.any(),
            Matchers.anyString(), (PortletRequest) Matchers.any(), (PortletResponse) Matchers.any());

    Mockito.when(_indexerRegistry.getIndexer(Mockito.anyString())).thenReturn(_indexer);

    Document document = SearchTestUtil.createAttachmentDocument(_DL_FILE_ENTRY_CLASS_NAME);

    String snippet = RandomTestUtil.randomString();

    document.add(new Field(Field.SNIPPET, snippet));

    try (CaptureHandler captureHandler = JDKLoggerTestUtil
            .configureJDKLogger(SearchResultTranslatorImpl.class.getName(), Level.WARNING)) {

        SearchResult searchResult = assertOneSearchResult(document);

        List<LogRecord> logRecords = captureHandler.getLogRecords();

        Assert.assertEquals(logRecords.toString(), 1, logRecords.size());

        LogRecord logRecord = logRecords.get(0);

        long entryClassPK = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

        Assert.assertEquals("Search index is stale and contains entry {" + entryClassPK + "}",
                logRecord.getMessage());

        Assert.assertEquals(SearchTestUtil.ATTACHMENT_OWNER_CLASS_NAME, searchResult.getClassName());
        Assert.assertEquals(SearchTestUtil.ATTACHMENT_OWNER_CLASS_PK, searchResult.getClassPK());
        Assert.assertNull(searchResult.getSummary());

        Mockito.verify(_indexerRegistry).getIndexer(_DL_FILE_ENTRY_CLASS_NAME);

        Mockito.verify(_indexer).getSummary(document, snippet, null, null);

        assertEmptyFileEntryRelatedSearchResults(searchResult);

        Mockito.verify(_dlAppLocalService).getFileEntry(SearchTestUtil.ENTRY_CLASS_PK);

        assertEmptyCommentRelatedSearchResults(searchResult);
        assertEmptyVersions(searchResult);
    }// ww w  . j  a  va2  s.  co  m
}

From source file:com.liferay.journal.search.SearchResultUtilJournalArticleTest.java

License:Open Source License

protected Document createDocument() {
    Document document = SearchTestUtil.createDocument(_JOURNAL_ARTICLE_CLASS_NAME);

    document.add(new Field(Field.VERSION, _DOCUMENT_VERSION));

    return document;
}

From source file:com.rivetlogic.portal.search.elasticsearch.util.ElasticsearchHelper.java

License:Open Source License

/**
 * Gets the documents.// w ww. j a  va  2 s . c  om
 *
 * @param searchHits the search hits
 * @return the documents
 */
private Document[] getDocuments(SearchHits searchHits) {
    if (_log.isInfoEnabled()) {
        _log.info("Getting document objects from SearchHits");
    }
    int total = Integer.parseInt((searchHits != null) ? String.valueOf(searchHits.getTotalHits()) : "0");
    int failedJsonCount = 0;
    if (total > 0) {
        List<Document> documentsList = new ArrayList<Document>(total);
        @SuppressWarnings("rawtypes")
        Iterator itr = searchHits.iterator();
        while (itr.hasNext()) {
            Document document = new DocumentImpl();
            SearchHit hit = (SearchHit) itr.next();

            JSONObject json;
            try {
                json = JSONFactoryUtil.createJSONObject(hit.getSourceAsString());
                @SuppressWarnings("rawtypes")
                Iterator jsonItr = json.keys();
                while (jsonItr.hasNext()) {
                    String key = (String) jsonItr.next();
                    String value = (String) json.getString(key);
                    if (_log.isDebugEnabled()) {
                        _log.debug(">>>>>>>>>> " + key + " : " + value);
                    }
                    document.add(new Field(key, value));
                }
                documentsList.add(document);
            } catch (JSONException e) {
                failedJsonCount++;
                _log.error("Error while processing the search result json objects", e);
            }
        }
        if (_log.isInfoEnabled()) {
            _log.info("Total size of the search results: " + documentsList.size());
        }
        return documentsList.toArray(new Document[documentsList.size() - failedJsonCount]);
    } else {
        if (_log.isInfoEnabled()) {
            _log.info("No search results found");
        }
        return new Document[0];
    }
}

From source file:com.rivetlogic.portal.search.elasticsearch.util.ElasticsearchHelper.java

License:Open Source License

/**
 * Gets the documents.//from  ww  w  .  j a va 2 s .c  o  m
 *
 * @param searchHits the search hits
 * @param searchContext the search context
 * @return the documents
 */
private Document[] getDocuments(SearchHits searchHits, SearchContext searchContext) {
    if (_log.isInfoEnabled()) {
        _log.info("Getting document objects from SearchHits");
    }

    String[] types = searchContext.getEntryClassNames();
    int total = Integer.parseInt((searchHits != null) ? String.valueOf(searchHits.getTotalHits()) : "0");
    int failedJsonCount = 0;
    String className = null;
    if (total > 0) {
        List<Document> documentsList = new ArrayList<Document>(total);
        @SuppressWarnings("rawtypes")
        Iterator itr = searchHits.iterator();
        while (itr.hasNext()) {
            Document document = new DocumentImpl();
            SearchHit hit = (SearchHit) itr.next();

            JSONObject json;
            try {
                json = JSONFactoryUtil.createJSONObject(hit.getSourceAsString());
                @SuppressWarnings("rawtypes")
                Iterator jsonItr = json.keys();
                while (jsonItr.hasNext()) {
                    String key = (String) jsonItr.next();
                    String value = (String) json.getString(key);
                    if (_log.isDebugEnabled()) {
                        _log.debug(">>>>>>>>>> " + key + " : " + value);
                    }
                    document.add(new Field(key, value));
                    if (key.equalsIgnoreCase("entryClassName")) {
                        className = value;
                    }
                }
                if (ArrayUtil.contains(types, className)) {
                    documentsList.add(document);
                }
            } catch (JSONException e) {
                failedJsonCount++;
                _log.error("Error while processing the search result json objects", e);
            }
        }
        if (_log.isInfoEnabled()) {
            _log.info("Total size of the search results: " + documentsList.size());
        }
        return documentsList.toArray(new Document[documentsList.size() - failedJsonCount]);
    } else {
        if (_log.isInfoEnabled()) {
            _log.info("No search results found");
        }
        return new Document[0];
    }
}

From source file:com.rknowsys.portal.search.elastic.ElasticsearchIndexSearcher.java

License:Open Source License

protected Document processSearchHit(SearchHit hit) {
    Document document = new DocumentImpl();

    Map<String, Object> source = hit.getSource();

    for (String fieldName : source.keySet()) {

        Object val = source.get(fieldName);
        if (val == null) {
            Field field = new Field(fieldName, (String) null);
            document.add(field);//w ww  . j a  v a 2 s  .c  om
        } else if (val instanceof List) {
            String[] values = ((List<String>) val).toArray(new String[((List<String>) val).size()]);
            Field field = new Field(fieldName, values);
            document.add(field);
        } else {
            Field field = new Field(fieldName, new String[] { val.toString() });
            document.add(field);
        }
    }

    return document;
}

From source file:org.opencps.dossiermgt.search.DossierFileIndexer.java

License:Open Source License

@Override
protected Document doGetDocument(Object obj) throws Exception {
    // TODO Auto-generated method stub
    DossierFile dossierFile = (DossierFile) obj;

    Document document = getBaseModelDocument(PORTLET_ID, dossierFile);

    if (dossierFile.getDisplayName() != null && !Validator.isBlank(dossierFile.getDisplayName())) {
        Field field = new Field(DossierFileDisplayTerms.DISPLAY_NAME,
                dossierFile.getDisplayName().toLowerCase().split("\\s+"));
        field.setBoost(5);/*from   w  w  w  .j  av  a2s.  co m*/
        document.add(field);
    }

    if (dossierFile.getModifiedDate() != null) {
        document.addDate(Field.MODIFIED_DATE, dossierFile.getModifiedDate());
    }
    if (dossierFile.getFormData() != null && !Validator.isBlank(dossierFile.getFormData())) {
        document.addText(DossierFileDisplayTerms.FORM_DATA,
                dossierFile.getFormData().toLowerCase().split("\\s+"));
    }
    if (dossierFile.getDossierFileNo() != null && !Validator.isBlank(dossierFile.getDossierFileNo())) {
        document.addText(DossierFileDisplayTerms.DOSSIER_FILE_NO, dossierFile.getDossierFileNo());
    }
    document.addNumber(DossierFileDisplayTerms.DOSSIER_FILE_ID, dossierFile.getDossierFileId());
    document.addKeyword(Field.GROUP_ID, getSiteGroupId(dossierFile.getGroupId()));
    document.addKeyword(Field.SCOPE_GROUP_ID, dossierFile.getGroupId());

    return document;
}

From source file:org.opencps.dossiermgt.search.DossierIndexer.java

License:Open Source License

@Override
protected Document doGetDocument(Object obj) throws Exception {
    // TODO Auto-generated method stub
    Dossier dossier = (Dossier) obj;/*from   ww  w .  j a  v  a 2 s.  c  o m*/

    Document document = getBaseModelDocument(PORTLET_ID, dossier);

    if (dossier.getReceptionNo() != null && !Validator.isBlank(dossier.getReceptionNo())) {
        Field field = new Field(DossierDisplayTerms.RECEPTION_NO, dossier.getReceptionNo());
        field.setBoost(5);
        document.add(field);
    }
    if (dossier.getModifiedDate() != null) {
        document.addDate(Field.MODIFIED_DATE, dossier.getModifiedDate());
    }
    if (dossier.getCityName() != null && !Validator.isBlank(dossier.getCityName())) {
        document.addText(DossierDisplayTerms.CITY_NAME, dossier.getCityName().toLowerCase().split("\\s+"));
    }
    if (dossier.getExternalRefNo() != null && !Validator.isBlank(dossier.getExternalRefNo())) {
        document.addText(DossierDisplayTerms.EXTERNALREF_NO, dossier.getExternalRefNo());
    }
    if (dossier.getExternalRefUrl() != null && !Validator.isBlank(dossier.getExternalRefUrl())) {
        document.addText(DossierDisplayTerms.EXTERNALREF_URL, dossier.getExternalRefUrl());
    }
    if (dossier.getGovAgencyName() != null && !Validator.isBlank(dossier.getGovAgencyName())) {
        document.addText(DossierDisplayTerms.GOVAGENCY_NAME,
                dossier.getGovAgencyName().toLowerCase().split("\\s+"));
    }
    if (dossier.getSubjectName() != null && !Validator.isBlank(dossier.getSubjectName())) {
        document.addText(DossierDisplayTerms.SUBJECT_NAME,
                dossier.getSubjectName().toLowerCase().split("\\s+"));
    }
    if (dossier.getAddress() != null && !Validator.isBlank(dossier.getAddress())) {
        document.addText(DossierDisplayTerms.ADDRESS, dossier.getAddress().toLowerCase().split("\\s+"));
    }
    if (dossier.getCityCode() != null && !Validator.isBlank(dossier.getCityCode())) {
        document.addText(DossierDisplayTerms.CITY_CODE, dossier.getCityCode());
    }
    if (dossier.getDistrictCode() != null && !Validator.isBlank(dossier.getDistrictCode())) {
        document.addText(DossierDisplayTerms.DISTRICT_CODE, dossier.getDistrictCode());
    }
    if (dossier.getDistrictName() != null && !Validator.isBlank(dossier.getDistrictName())) {
        document.addText(DossierDisplayTerms.DISTRICT_NAME,
                dossier.getDistrictName().toLowerCase().split("\\s+"));
    }
    if (dossier.getWardCode() != null && !Validator.isBlank(dossier.getWardCode())) {
        document.addText(DossierDisplayTerms.WARD_CODE, dossier.getWardCode());
    }
    if (dossier.getWardName() != null && !Validator.isBlank(dossier.getWardName())) {
        document.addText(DossierDisplayTerms.WARD_NAME, dossier.getWardName().toLowerCase().split("\\s+"));
    }
    if (dossier.getContactName() != null && !Validator.isBlank(dossier.getContactName())) {
        document.addText(DossierDisplayTerms.CONTACT_NAME,
                dossier.getContactName().toLowerCase().split("\\s+"));
    }
    if (dossier.getContactTelNo() != null && !Validator.isBlank(dossier.getContactTelNo())) {
        document.addText(DossierDisplayTerms.CONTACT_TEL_NO, dossier.getContactTelNo());
    }
    if (dossier.getContactEmail() != null && !Validator.isBlank(dossier.getContactEmail())) {
        document.addText(DossierDisplayTerms.CONTACT_EMAIL, dossier.getContactEmail());
    }
    if (dossier.getNote() != null && !Validator.isBlank(dossier.getNote())) {
        document.addText(DossierDisplayTerms.NOTE, dossier.getNote().toLowerCase().split("\\s+"));
    }
    document.addNumber(DossierDisplayTerms.DOSSIER_ID, dossier.getDossierId());

    document.addKeyword(Field.GROUP_ID, getSiteGroupId(dossier.getGroupId()));
    document.addKeyword(Field.SCOPE_GROUP_ID, dossier.getGroupId());

    return document;
}

From source file:org.rsc.liferay.solr.SolrIndexSearcher.java

License:Open Source License

protected Hits subset(SolrQuery solrQuery, Query query, QueryConfig queryConfig, QueryResponse queryResponse,
        boolean allResults) throws Exception {

    long startTime = System.currentTimeMillis();

    Hits hits = new HitsImpl();

    SolrDocumentList solrDocumentList = queryResponse.getResults();

    long total = solrDocumentList.getNumFound();

    if (allResults && (total > 0)) {
        solrQuery.setRows((int) total);

        queryResponse = _solrServer.query(solrQuery);

        return subset(solrQuery, query, queryConfig, queryResponse, false);
    }//from   w  ww  .  ja  v  a 2 s .c o  m

    List<Document> documents = new ArrayList<Document>();
    List<Float> scores = new ArrayList<Float>();
    List<String> snippets = new ArrayList<String>();

    float maxScore = -1;
    Set<String> queryTerms = new HashSet<String>();
    int subsetTotal = 0;

    for (SolrDocument solrDocument : solrDocumentList) {
        Document document = new DocumentImpl();

        Collection<String> names = solrDocument.getFieldNames();

        for (String name : names) {
            Collection<Object> fieldValues = solrDocument.getFieldValues(name);

            Field field = new Field(name,
                    ArrayUtil.toStringArray(fieldValues.toArray(new Object[fieldValues.size()])));

            document.add(field);
        }

        documents.add(document);

        String snippet = StringPool.BLANK;

        if (queryConfig.isHighlightEnabled()) {
            snippet = getSnippet(solrDocument, queryConfig, queryTerms, queryResponse.getHighlighting(),
                    Field.CONTENT);

            if (Validator.isNull(snippet)) {
                snippet = getSnippet(solrDocument, queryConfig, queryTerms, queryResponse.getHighlighting(),
                        Field.TITLE);
            }

            if (Validator.isNotNull(snippet)) {
                snippets.add(snippet);
            }
        }

        if (queryConfig.isScoreEnabled()) {
            float score = GetterUtil.getFloat(String.valueOf(solrDocument.getFieldValue("score")));

            if (score > maxScore) {
                maxScore = score;
            }

            scores.add(score);
        } else {
            scores.add(maxScore);
        }

        subsetTotal++;
    }

    hits.setDocs(documents.toArray(new Document[subsetTotal]));
    hits.setLength((int) total);
    hits.setQuery(query);
    hits.setQueryTerms(queryTerms.toArray(new String[queryTerms.size()]));

    Float[] scoresArray = scores.toArray(new Float[subsetTotal]);

    if (queryConfig.isScoreEnabled() && (subsetTotal > 0) && (maxScore > 0)) {

        for (int i = 0; i < scoresArray.length; i++) {
            scoresArray[i] = scoresArray[i] / maxScore;
        }
    }

    hits.setScores(scoresArray);

    float searchTime = (float) (System.currentTimeMillis() - startTime) / Time.SECOND;

    hits.setSearchTime(searchTime);
    hits.setSnippets(snippets.toArray(new String[subsetTotal]));
    hits.setStart(startTime);

    return hits;
}