Example usage for com.liferay.portal.kernel.search Hits setSearchTime

List of usage examples for com.liferay.portal.kernel.search Hits setSearchTime

Introduction

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

Prototype

public void setSearchTime(float time);

Source Link

Usage

From source file:com.liferay.document.library.repository.cmis.internal.CMISRepository.java

License:Open Source License

protected Hits doSearch(SearchContext searchContext, Query query) throws Exception {

    long startTime = System.currentTimeMillis();

    Session session = getSession();//from   w ww .  j  a  va2  s. com

    RepositoryInfo repositoryInfo = session.getRepositoryInfo();

    RepositoryCapabilities repositoryCapabilities = repositoryInfo.getCapabilities();

    QueryConfig queryConfig = searchContext.getQueryConfig();

    CapabilityQuery capabilityQuery = repositoryCapabilities.getQueryCapability();

    queryConfig.setAttribute("capabilityQuery", capabilityQuery.value());

    String productName = repositoryInfo.getProductName();
    String productVersion = repositoryInfo.getProductVersion();

    queryConfig.setAttribute("repositoryProductName", productName);
    queryConfig.setAttribute("repositoryProductVersion", productVersion);

    String queryString = _cmisSearchQueryBuilder.buildQuery(searchContext, query);

    if (_cmisRepositoryDetector.isNuxeo5_4()) {
        queryString += " AND (" + PropertyIds.IS_LATEST_VERSION + " = true)";
    }

    if (_log.isDebugEnabled()) {
        _log.debug("CMIS search query: " + queryString);
    }

    boolean searchAllVersions = _cmisRepositoryDetector.isNuxeo5_5OrHigher();

    ItemIterable<QueryResult> queryResults = session.query(queryString, searchAllVersions);

    int start = searchContext.getStart();
    int end = searchContext.getEnd();

    if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) {
        start = 0;
    }

    int total = 0;

    List<com.liferay.portal.kernel.search.Document> documents = new ArrayList<>();
    List<String> snippets = new ArrayList<>();
    List<Float> scores = new ArrayList<>();

    for (QueryResult queryResult : queryResults) {
        total++;

        if (total <= start) {
            continue;
        }

        if ((total > end) && (end != QueryUtil.ALL_POS)) {
            continue;
        }

        com.liferay.portal.kernel.search.Document document = new DocumentImpl();

        String objectId = queryResult.getPropertyValueByQueryName(PropertyIds.OBJECT_ID);

        if (_log.isDebugEnabled()) {
            _log.debug("Search result object ID " + objectId);
        }

        FileEntry fileEntry = null;

        try {
            fileEntry = toFileEntry(objectId, true);
        } catch (Exception e) {
            if (_log.isDebugEnabled()) {
                Throwable cause = e.getCause();

                if (cause != null) {
                    cause = cause.getCause();
                }

                if (cause instanceof CmisObjectNotFoundException) {
                    _log.debug("Search result ignored for CMIS document which "
                            + "has a version with an invalid object ID " + cause.getMessage());
                } else {
                    _log.debug("Search result ignored for invalid object ID", e);
                }
            }

            total--;

            continue;
        }

        DocumentHelper documentHelper = new DocumentHelper(document);

        documentHelper.setEntryKey(fileEntry.getModelClassName(), fileEntry.getFileEntryId());

        document.addKeyword(Field.TITLE, fileEntry.getTitle());

        documents.add(document);

        if (queryConfig.isScoreEnabled()) {
            Object scoreObj = queryResult.getPropertyValueByQueryName("HITS");

            if (scoreObj != null) {
                scores.add(Float.valueOf(scoreObj.toString()));
            } else {
                scores.add(1.0F);
            }
        } else {
            scores.add(1.0F);
        }

        snippets.add(StringPool.BLANK);
    }

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

    Hits hits = new HitsImpl();

    hits.setDocs(documents.toArray(new com.liferay.portal.kernel.search.Document[documents.size()]));
    hits.setLength(total);
    hits.setQuery(query);
    hits.setQueryTerms(new String[0]);
    hits.setScores(ArrayUtil.toFloatArray(scores));
    hits.setSearchTime(searchTime);
    hits.setSnippets(snippets.toArray(new String[snippets.size()]));
    hits.setStart(startTime);

    return hits;
}

From source file:com.liferay.document.library.repository.external.ExtRepositoryAdapter.java

License:Open Source License

@Override
public Hits search(SearchContext searchContext, Query query) throws SearchException {

    long startTime = System.currentTimeMillis();

    List<ExtRepositorySearchResult<?>> extRepositorySearchResults = null;

    try {/*from w w  w .j a  va 2 s  .  c  om*/
        extRepositorySearchResults = _extRepository.search(searchContext, query,
                new ExtRepositoryQueryMapperImpl(this));
    } catch (PortalException | SystemException e) {
        throw new SearchException("Unable to perform search", e);
    }

    QueryConfig queryConfig = searchContext.getQueryConfig();

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

    int total = 0;

    for (ExtRepositorySearchResult<?> extRepositorySearchResult : extRepositorySearchResults) {

        try {
            ExtRepositoryObjectAdapter<?> extRepositoryEntryAdapter = _toExtRepositoryObjectAdapter(
                    ExtRepositoryObjectAdapterType.OBJECT, extRepositorySearchResult.getObject());

            Document document = new DocumentImpl();

            document.addKeyword(Field.ENTRY_CLASS_NAME, extRepositoryEntryAdapter.getModelClassName());
            document.addKeyword(Field.ENTRY_CLASS_PK, extRepositoryEntryAdapter.getPrimaryKey());
            document.addKeyword(Field.TITLE, extRepositoryEntryAdapter.getName());

            documents.add(document);

            if (queryConfig.isScoreEnabled()) {
                scores.add(extRepositorySearchResult.getScore());
            } else {
                scores.add(1.0F);
            }

            snippets.add(extRepositorySearchResult.getSnippet());

            total++;
        } catch (PortalException | SystemException e) {
            if (_log.isWarnEnabled()) {
                _log.warn("Invalid entry returned from search", e);
            }
        }
    }

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

    Hits hits = new HitsImpl();

    hits.setDocs(documents.toArray(new Document[documents.size()]));
    hits.setLength(total);
    hits.setQueryTerms(new String[0]);
    hits.setScores(ArrayUtil.toFloatArray(scores));
    hits.setSearchTime(searchTime);
    hits.setSnippets(snippets.toArray(new String[snippets.size()]));
    hits.setStart(startTime);

    return hits;
}

From source file:com.liferay.journal.content.search.web.internal.util.ContentHits.java

License:Open Source License

public void recordHits(Hits hits, long groupId, boolean privateLayout, int start, int end) throws Exception {

    // This can later be optimized according to LEP-915.

    List<Document> docs = new ArrayList<>();
    List<Float> scores = new ArrayList<>();

    Document[] docsArray = hits.getDocs();

    for (int i = 0; i < docsArray.length; i++) {
        Document doc = hits.doc(i);

        String articleId = doc.get(Field.ARTICLE_ID);
        long articleGroupId = GetterUtil.getLong(doc.get(Field.GROUP_ID));

        int layoutIdsCount = JournalContentSearchLocalServiceUtil.getLayoutIdsCount(groupId, privateLayout,
                articleId);/*  w ww.  ja v  a  2 s.  c  o  m*/

        if ((layoutIdsCount > 0) || (!isShowListed() && (articleGroupId == groupId))) {

            docs.add(hits.doc(i));
            scores.add(hits.score(i));
        }
    }

    int length = docs.size();

    hits.setLength(length);

    if (end > length) {
        end = length;
    }

    docs = docs.subList(start, end);
    scores = scores.subList(start, end);

    hits.setDocs(docs.toArray(new Document[docs.size()]));
    hits.setScores(ArrayUtil.toFloatArray(scores));

    hits.setSearchTime((float) (System.currentTimeMillis() - hits.getStart()) / Time.SECOND);
}

From source file:com.liferay.portlet.journalcontentsearch.util.ContentHits.java

License:Open Source License

public void recordHits(Hits hits, long groupId, boolean privateLayout, int start, int end) throws Exception {

    // This can later be optimized according to LEP-915.

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

    for (int i = 0; i < hits.getLength(); i++) {
        Document doc = hits.doc(i);

        long articleGroupId = GetterUtil.getLong(doc.get(Field.GROUP_ID));
        String articleId = doc.get("articleId");

        if (JournalContentSearchLocalServiceUtil.getLayoutIdsCount(groupId, privateLayout, articleId) > 0) {

            docs.add(hits.doc(i));/*from w w  w .  j  av a  2  s . c o m*/
            scores.add(hits.score(i));
            snippets.add(hits.snippet(i));
        } else if (!isShowListed() && (articleGroupId == groupId)) {
            docs.add(hits.doc(i));
            scores.add(hits.score(i));
            snippets.add(hits.snippet(i));
        }
    }

    int length = docs.size();

    hits.setLength(length);

    if (end > length) {
        end = length;
    }

    docs = docs.subList(start, end);
    scores = scores.subList(start, end);
    snippets = snippets.subList(start, end);

    hits.setDocs(docs.toArray(new Document[docs.size()]));
    hits.setScores(scores.toArray(new Float[docs.size()]));
    hits.setSnippets(snippets.toArray(new String[docs.size()]));

    hits.setSearchTime((float) (System.currentTimeMillis() - hits.getStart()) / Time.SECOND);
}

From source file:com.liferay.repository.external.ExtRepositoryAdapter.java

License:Open Source License

@Override
public Hits search(SearchContext searchContext, Query query) throws SearchException {

    long startTime = System.currentTimeMillis();

    List<ExtRepositorySearchResult<?>> extRepositorySearchResults = null;

    try {//from   w  w  w. j  a v a  2  s  .  c  om
        extRepositorySearchResults = _extRepository.search(searchContext, query,
                new ExtRepositoryQueryMapperImpl(this));
    } catch (PortalException pe) {
        throw new SearchException("Unable to perform search", pe);
    } catch (SystemException se) {
        throw new SearchException("Unable to perform search", se);
    }

    QueryConfig queryConfig = searchContext.getQueryConfig();

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

    int total = 0;

    for (ExtRepositorySearchResult<?> extRepositorySearchResult : extRepositorySearchResults) {

        try {
            ExtRepositoryObjectAdapter<?> extRepositoryEntryAdapter = _toExtRepositoryObjectAdapter(
                    ExtRepositoryObjectAdapterType.OBJECT, extRepositorySearchResult.getObject());

            Document document = new DocumentImpl();

            document.addKeyword(Field.ENTRY_CLASS_NAME, extRepositoryEntryAdapter.getModelClassName());
            document.addKeyword(Field.ENTRY_CLASS_PK, extRepositoryEntryAdapter.getPrimaryKey());
            document.addKeyword(Field.TITLE, extRepositoryEntryAdapter.getName());

            documents.add(document);

            if (queryConfig.isScoreEnabled()) {
                scores.add(extRepositorySearchResult.getScore());
            } else {
                scores.add(1.0F);
            }

            snippets.add(extRepositorySearchResult.getSnippet());

            total++;
        } catch (SystemException se) {
            if (_log.isWarnEnabled()) {
                _log.warn("Invalid entry returned from search", se);
            }
        } catch (PortalException pe) {
            if (_log.isWarnEnabled()) {
                _log.warn("Invalid entry returned from search", pe);
            }
        }
    }

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

    Hits hits = new HitsImpl();

    hits.setDocs(documents.toArray(new Document[documents.size()]));
    hits.setLength(total);
    hits.setQueryTerms(new String[0]);
    hits.setScores(ArrayUtil.toFloatArray(scores));
    hits.setSearchTime(searchTime);
    hits.setSnippets(snippets.toArray(new String[snippets.size()]));
    hits.setStart(startTime);

    return hits;
}

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

License:Open Source License

/**
 * Gets the search hits./*from w  w  w. ja v  a  2  s  . c  o m*/
 *
 * @param searchContext the search context
 * @param query the query
 * @return the search hits
 */
public Hits getSearchHits(SearchContext searchContext, Query query) {
    if (_log.isInfoEnabled()) {
        _log.info("Search against Elasticsearch with SearchContext");
    }
    Hits hits = new HitsImpl();
    hits.setStart(new Date().getTime());

    Client client = this._esConnector.getClient();

    String keywords = searchContext.getKeywords();
    SearchRequestBuilder searchRequestBuilder = client
            .prepareSearch(ElasticsearchIndexerConstants.ELASTIC_SEARCH_LIFERAY_INDEX)
            .setQuery(_esQueryBuilder.doSearch(query));

    // Handle Search Facet queries
    handleFacetQueries(searchContext, searchRequestBuilder);
    SearchResponse response = null;
    if (getSort(searchContext.getSorts()) != null) {
        searchRequestBuilder = searchRequestBuilder.setFrom(searchContext.getStart())
                .setSize(searchContext.getEnd()).addSort(getSort(searchContext.getSorts()));
    } else {
        searchRequestBuilder = searchRequestBuilder.setFrom(searchContext.getStart())
                .setSize(searchContext.getEnd());
    }
    response = searchRequestBuilder.execute().actionGet();
    collectFacetResults(searchContext, response);

    SearchHits searchHits = response.getHits();
    hits.setDocs(getDocuments(searchHits, searchContext));
    hits.setScores(getScores(searchHits));
    hits.setSearchTime((float) (System.currentTimeMillis() - hits.getStart()) / Time.SECOND);
    hits.setQuery(query);
    if (keywords != null) {
        hits.setQueryTerms(keywords.split(StringPool.SPACE));
    }
    hits.setLength((int) searchHits.getTotalHits());
    hits.setStart(hits.getStart());

    return hits;
}

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

License:Open Source License

/**
 * Gets the search hits.//  w w  w . j a  v  a 2  s  . c o  m
 *
 * @param searchEngineId the search engine id
 * @param companyId the company id
 * @param query the query
 * @param sort the sort
 * @param start the start
 * @param end the end
 * @return the search hits
 */
public Hits getSearchHits(String searchEngineId, long companyId, Query query, Sort[] sort, int start, int end) {
    if (_log.isInfoEnabled()) {
        _log.info(
                "Search against Elasticsearch with searchEngineId, companyId, query, sort, start and end parameters");
    }
    Hits hits = new HitsImpl();
    Client client = this._esConnector.getClient();

    SearchRequestBuilder searchRequestBuilder = client
            .prepareSearch(ElasticsearchIndexerConstants.ELASTIC_SEARCH_LIFERAY_INDEX)
            .setQuery(_esQueryBuilder.doSearch(query));
    SearchResponse response = null;
    if (getSort(sort) != null) {
        response = searchRequestBuilder.setFrom(start).setSize(end).addSort(getSort(sort)).execute()
                .actionGet();
    } else {
        response = searchRequestBuilder.setFrom(start).setSize(end).execute().actionGet();
    }
    SearchHits searchHits = response.getHits();
    hits.setDocs(getDocuments(searchHits));
    hits.setScores(getScores(searchHits));
    hits.setSearchTime((float) (System.currentTimeMillis() - hits.getStart()) / Time.SECOND);
    hits.setQuery(query);
    hits.setLength((int) searchHits.getTotalHits());
    hits.setStart(hits.getStart());

    return hits;
}

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

License:Open Source License

private Hits doSearch(SearchContext searchContext, Query query, int start, int end) {
    Client client = getClient();/*from   w  ww  .  j  a v a  2s . c o  m*/

    SearchRequestBuilder searchRequestBuilder = prepareSearchBuilder(searchContext, query, client, start, end);
    _log.debug("Current lucene version:  " + Version.LUCENE_CURRENT);
    _log.debug("Search query String  " + searchRequestBuilder.toString());
    SearchRequest searchRequest = searchRequestBuilder.request();
    _log.debug("Time Before request to ES: " + System.currentTimeMillis());
    ActionFuture<SearchResponse> future = client.search(searchRequest);
    SearchResponse searchResponse = future.actionGet();
    _log.debug("Time After response from ES: " + System.currentTimeMillis());
    updateFacetCollectors(searchContext, searchResponse);
    Hits hits = processSearchHits(searchResponse, query.getQueryConfig());
    _log.debug("Total responseCount  " + searchResponse.getHits().getTotalHits());
    _log.debug("Time After processSearchHits: " + System.currentTimeMillis());

    hits.setQuery(query);

    TimeValue timeValue = searchResponse.getTook();

    hits.setSearchTime((float) timeValue.getSecondsFrac());
    return hits;
}

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

License:Open Source License

@Override
public Hits search(String searchEngineId, long companyId, Query query, Sort[] sort, int start, int end)
        throws SearchException {

    try {//from  w  w w .j ava 2 s . c  om
        Client client = getClient();
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch(Utilities.getIndexName(companyId));
        String q = applyCustomESRules(query.toString());

        QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(q);

        searchRequestBuilder.setQuery(queryBuilder);

        searchRequestBuilder.setTypes("documents");

        addSortToSearch(sort, searchRequestBuilder);

        _log.debug("Search Start:  " + start + " Search End: " + end);
        if ((start != QueryUtil.ALL_POS) && (end != QueryUtil.ALL_POS)) {
            searchRequestBuilder.setFrom(start).setSize(end - start);
        }

        _log.debug("Query String" + searchRequestBuilder.toString());

        SearchRequest searchRequest = searchRequestBuilder.request();

        _log.debug("Search query String  " + searchRequest.toString());

        ActionFuture<SearchResponse> future = client.search(searchRequest);

        SearchResponse searchResponse = future.actionGet();

        Hits hits = processSearchHits(searchResponse, query.getQueryConfig());

        hits.setQuery(query);

        TimeValue timeValue = searchResponse.getTook();

        hits.setSearchTime((float) timeValue.getSecondsFrac());
        return hits;
    } catch (Exception e) {
        throw new SearchException(e);
    }
}

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);
    }/* w  ww  . j a va 2  s  .  c  om*/

    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;
}