Example usage for com.liferay.portal.kernel.search Document getFields

List of usage examples for com.liferay.portal.kernel.search Document getFields

Introduction

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

Prototype

public Map<String, Field> getFields();

Source Link

Usage

From source file:com.liferay.alloy.mvc.BaseAlloyControllerImpl.java

License:Open Source License

protected JSONObject toJSONObject(Document document) {
    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    Map<String, Field> fields = document.getFields();

    for (String key : fields.keySet()) {
        Field field = fields.get(key);

        jsonObject.put(field.getName(), field.getValue());
    }/*from  w  ww .j  a  v  a2s . co  m*/

    return jsonObject;
}

From source file:com.liferay.document.library.search.test.DLFileEntryIndexerLocalizedContentTest.java

License:Open Source License

private static List<String> _getFieldValues(String prefix, Document document) {

    List<String> filteredFields = new ArrayList<>();

    Map<String, Field> fields = document.getFields();

    for (String field : fields.keySet()) {
        if (field.contains(prefix)) {
            filteredFields.add(field);/*from   www  .  j  a  v  a 2  s  .c o  m*/
        }
    }

    return filteredFields;
}

From source file:com.liferay.journal.search.test.JournalArticleIndexerLocalizedContentTest.java

License:Open Source License

private String _getDDMNumber(Document document) {
    Map<String, Field> map = document.getFields();

    Set<String> keys = map.keySet();

    Stream<String> names = keys.stream();

    String prefix = "ddm__text__";

    Stream<String> ddmNames = names.filter(name -> name.startsWith(prefix));

    Stream<String> ddmNumbers = ddmNames.map(name -> name.substring(prefix.length(), prefix.length() + 5));

    Optional<String> ddmNumberOptional = ddmNumbers.findAny();

    return ddmNumberOptional.orElseThrow(IllegalStateException::new);
}

From source file:com.liferay.journal.test.util.FieldValuesAssert.java

License:Open Source License

private static Map<String, String> _getFieldValues(String prefix, Document document) {

    Map<String, Field> fieldsMap = document.getFields();

    Set<Entry<String, Field>> entrySet = fieldsMap.entrySet();

    Stream<Entry<String, Field>> entries = entrySet.stream();

    Stream<Entry<String, Field>> prefixedEntries = entries.filter(entry -> {
        String name = entry.getKey();

        return name.startsWith(prefix);
    });// w w w. j a  v a2  s  . c om

    return prefixedEntries.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
        Field field = entry.getValue();

        return field.getValue();
    }));
}

From source file:com.rivetlogic.portal.search.elasticsearch.indexer.document.ElasticsearchDocumentJSONBuilder.java

License:Open Source License

/**
 * Convert to json./*  w w w .  j ava 2s  .co m*/
 * 
 * @param document
 *            the document
 * @return the string
 */
public ElasticserachJSONDocument convertToJSON(final Document document) {

    Map<String, Field> fields = document.getFields();
    ElasticserachJSONDocument elasticserachJSONDocument = new ElasticserachJSONDocument();

    try {
        XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject();

        Field classnameField = document.getField(ElasticsearchIndexerConstants.ENTRY_CLASSNAME);
        String entryClassName = (classnameField == null) ? "" : classnameField.getValue();

        /**
         * Handle all error scenarios prior to conversion
         */
        if (isDocumentHidden(document)) {
            elasticserachJSONDocument.setError(true);
            elasticserachJSONDocument
                    .setErrorMessage(ElasticserachJSONDocument.DocumentError.HIDDEN_DOCUMENT.toString());
            return elasticserachJSONDocument;
        }
        if (entryClassName.isEmpty()) {
            elasticserachJSONDocument.setError(true);
            elasticserachJSONDocument
                    .setErrorMessage(ElasticserachJSONDocument.DocumentError.MISSING_ENTRYCLASSNAME.toString());
            return elasticserachJSONDocument;
        }
        if (isExcludedType(entryClassName)) {
            elasticserachJSONDocument.setError(true);
            elasticserachJSONDocument.setErrorMessage("Index Type:" + entryClassName + StringPool.COMMA
                    + ElasticserachJSONDocument.DocumentError.EXCLUDED_TYPE.toString());
            return elasticserachJSONDocument;
        }

        /**
         * To avoid multiple documents for versioned assets such as Journal articles, DL entry etc
         * the primary Id will be Indextype + Entry class PK. The primary Id is to maintain uniqueness
         * in ES server database and nothing to do with UID or is not used for any other purpose.
         */
        Field classPKField = document.getField(ElasticsearchIndexerConstants.ENTRY_CLASSPK);
        String entryClassPK = (classPKField == null) ? "" : classPKField.getValue();
        if (entryClassPK.isEmpty()) {
            elasticserachJSONDocument.setError(true);
            elasticserachJSONDocument
                    .setErrorMessage(ElasticserachJSONDocument.DocumentError.MISSING_CLASSPK.toString());
            return elasticserachJSONDocument;
        }

        /** Replace '.' by '_' in Entry class name,since '.' is not recommended by Elasticsearch in Index type */
        String indexType = entryClassName.replace(StringPool.PERIOD, StringPool.UNDERLINE);
        elasticserachJSONDocument.setIndexType(indexType);

        elasticserachJSONDocument.setId(indexType + entryClassPK);

        /** Create a JSON string for remaining fields of document */
        for (Iterator<Map.Entry<String, Field>> it = fields.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, Field> entry = it.next();
            Field field = entry.getValue();
            contentBuilder.field(entry.getKey(), field.getValue());
        }
        contentBuilder.endObject();

        elasticserachJSONDocument.setJsonDocument(contentBuilder.string());
        if (_log.isDebugEnabled()) {
            _log.debug("Liferay Document converted to ESJSON document successfully:" + contentBuilder.string());
        }
    } catch (IOException e) {
        _log.error("IO Error during converstion of Liferay Document to JSON format" + e.getMessage());
    }
    return elasticserachJSONDocument;
}

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

License:Open Source License

private String getElasticsearchDocument(Document document) throws IOException {

    XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();

    xContentBuilder.startObject();//from  w ww .ja  v  a 2  s  .  c o m

    Map<String, Field> fields = document.getFields();
    for (Field field : fields.values()) {
        String name = field.getName();

        if (!field.isLocalized()) {

            if (field.isNumeric()) {
                Class clazz = field.getNumericClass();
                if (clazz.equals(Double.class)) {
                    double[] values = GetterUtil.getDoubleValues(field.getValues());
                    if (values.length > 1) {
                        xContentBuilder.field(name, values);
                    } else {
                        xContentBuilder.field(name, values[0]);
                    }
                } else if (clazz.equals(Float.class)) {
                    float[] values = GetterUtil.getFloatValues(field.getValues());
                    if (values.length > 1) {
                        xContentBuilder.field(name, values);
                    } else {
                        xContentBuilder.field(name, values[0]);
                    }
                } else if (clazz.equals(Integer.class)) {
                    int[] values = GetterUtil.getIntegerValues(field.getValues());
                    if (values.length > 1) {
                        xContentBuilder.field(name, values);
                    } else {
                        xContentBuilder.field(name, values[0]);
                    }
                } else {
                    long[] values = GetterUtil.getLongValues(field.getValues());
                    if (values.length > 1) {
                        xContentBuilder.field(name, values);
                    } else {
                        xContentBuilder.field(name, values[0]);
                    }
                }
            } else {

                if (field.getValues().length > 1) {
                    xContentBuilder.field(name, field.getValues());
                } else {
                    xContentBuilder.field(name, field.getValue());
                }
            }
        } else {
            Map<Locale, String> localizedValues = field.getLocalizedValues();

            for (Map.Entry<Locale, String> entry : localizedValues.entrySet()) {

                String value = entry.getValue();

                if (Validator.isNull(value)) {
                    continue;
                }

                Locale locale = entry.getKey();

                String languageId = LocaleUtil.toLanguageId(locale);

                String defaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

                if (languageId.equals(defaultLanguageId)) {
                    xContentBuilder.field(name, value.trim());
                }

                String localizedName = DocumentImpl.getLocalizedName(LocaleUtil.fromLanguageId(languageId),
                        name);

                xContentBuilder.field(localizedName, value.trim());
            }
        }
    }

    xContentBuilder.endObject();

    return xContentBuilder.string();
}

From source file:com.vportal.portal.search.HitsOpenSearchImpl.java

License:Open Source License

public String search(HttpServletRequest request, long groupId, long userId, String keywords, int startPage,
        int itemsPerPage, String format) throws SearchException {

    try {//from w w w  .j a va2  s .com
        ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

        int start = (startPage * itemsPerPage) - itemsPerPage;
        int end = startPage * itemsPerPage;

        SearchContext searchContext = SearchContextFactory.getInstance(request);

        searchContext.setGroupIds(new long[] { groupId });
        searchContext.setEnd(end);
        searchContext.setKeywords(keywords);
        searchContext.setScopeStrict(false);
        searchContext.setStart(start);
        searchContext.setUserId(userId);

        addSearchAttributes(themeDisplay.getCompanyId(), searchContext, keywords);

        Portlet portlet = PortletLocalServiceUtil.getPortletById(themeDisplay.getCompanyId(), getPortletId());

        Indexer indexer = portlet.getIndexerInstance();

        Hits results = indexer.search(searchContext);

        String[] queryTerms = results.getQueryTerms();

        int total = results.getLength();

        Object[] values = addSearchResults(queryTerms, keywords, startPage, itemsPerPage, total, start,
                getTitle(keywords), getSearchPath(), format, themeDisplay);

        com.liferay.portal.kernel.xml.Document doc = (com.liferay.portal.kernel.xml.Document) values[0];
        Element root = (Element) values[1];

        for (int i = 0; i < results.getDocs().length; i++) {
            Document result = results.doc(i);

            String portletId = result.get(Field.PORTLET_ID);

            String snippet = results.snippet(i);

            long resultGroupId = GetterUtil.getLong(result.get(Field.GROUP_ID));

            PortletURL portletURL = getPortletURL(request, portletId, resultGroupId);

            Summary summary = getSummary(indexer, result, snippet, portletURL);

            String title = summary.getTitle();
            String url = getURL(themeDisplay, resultGroupId, result, portletURL);
            Date modifedDate = result.getDate(Field.MODIFIED);
            String content = summary.getContent();

            String[] tags = new String[0];

            Field assetTagNamesField = result.getFields().get(Field.ASSET_TAG_NAMES);

            if (assetTagNamesField != null) {
                tags = assetTagNamesField.getValues();
            }

            double ratings = 0.0;

            String entryClassName = result.get(Field.ENTRY_CLASS_NAME);
            long entryClassPK = GetterUtil.getLong(result.get(Field.ENTRY_CLASS_PK));

            if ((Validator.isNotNull(entryClassName)) && (entryClassPK > 0)) {

                RatingsStats stats = RatingsStatsLocalServiceUtil.getStats(entryClassName, entryClassPK);

                ratings = stats.getTotalScore();
            }

            double score = results.score(i);

            addSearchResult(root, resultGroupId, entryClassName, entryClassPK, title, url, modifedDate, content,
                    tags, ratings, score, format);
        }

        if (_log.isDebugEnabled()) {
            _log.debug("Return\n" + doc.asXML());
        }

        return doc.asXML();
    } catch (Exception e) {
        throw new SearchException(e);
    }
}

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

License:Open Source License

protected SolrInputDocument getSolrInputDocument(Document document) {
    SolrInputDocument solrInputDocument = new SolrInputDocument();

    Collection<Field> fields = document.getFields().values();

    for (Field field : fields) {
        String name = field.getName();
        float boost = field.getBoost();

        if (ArrayUtil.contains(Field.UNSCORED_FIELD_NAMES, name)) {
            boost = _UNSCORED_FIELDS_BOOST;
        }/* w w  w.ja  v a2 s.c  o m*/

        if (!field.isLocalized()) {
            for (String value : field.getValues()) {
                if (Validator.isNull(value)) {
                    continue;
                }

                solrInputDocument.addField(name, value.trim(), boost);
            }
        } else {
            Map<Locale, String> localizedValues = field.getLocalizedValues();

            for (Map.Entry<Locale, String> entry : localizedValues.entrySet()) {

                String value = entry.getValue();

                if (Validator.isNull(value)) {
                    continue;
                }

                Locale locale = entry.getKey();

                String languageId = LocaleUtil.toLanguageId(locale);

                String defaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

                if (languageId.equals(defaultLanguageId)) {
                    solrInputDocument.addField(name, value.trim(), boost);
                }

                String localizedName = DocumentImpl.getLocalizedName(locale, name);

                solrInputDocument.addField(localizedName, value.trim(), boost);
            }
        }
    }

    return solrInputDocument;
}