Java Code Examples for org.elasticsearch.search.SearchHit#field()

The following examples show how to use org.elasticsearch.search.SearchHit#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: JdbcResponseExtractor.java    From elasticsearch-sql with MIT License 6 votes vote down vote up
public JdbcSearchResponse parseSearchResponse(SearchResponse response,Map<String,String> aliasMap) {
    JdbcSearchResponse jdbcSearchResponse = new JdbcSearchResponse();
    jdbcSearchResponse.setSize(response.getHits().getHits().length);
    jdbcSearchResponse.setTook(response.getTook().getMillis());
    if (response.getHits().getTotalHits() != null) {
        jdbcSearchResponse.setTotal(response.getHits().getTotalHits().value);
    }
    SearchHit[] searchHits = response.getHits().getHits();
    if (searchHits != null && searchHits.length > 0) {
        List<Map<String, Object>> result = new ArrayList<>(searchHits.length);
        for (SearchHit hit : response.getHits().getHits()) {
            hit.getSourceAsMap().put("_id", hit.getId());
            if (hit.field("_routing") != null) {
                hit.getSourceAsMap().put("_routing", hit.field("_routing").getValue());
            }
            result.add(hit.getSourceAsMap());
        }
        jdbcSearchResponse.setResult(result);
        jdbcSearchResponse.setAliasMap(aliasMap);
    }
    return jdbcSearchResponse;
}
 
Example 2
Source File: ElasticSearchSearcher.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Flux<MessageSearchIndex.SearchResult> extractContentFromHit(SearchHit hit) {
    DocumentField mailboxId = hit.field(JsonMessageConstants.MAILBOX_ID);
    DocumentField uid = hit.field(JsonMessageConstants.UID);
    Optional<DocumentField> id = retrieveMessageIdField(hit);
    if (mailboxId != null && uid != null) {
        Number uidAsNumber = uid.getValue();
        return Flux.just(
            new MessageSearchIndex.SearchResult(
                id.map(field -> messageIdFactory.fromString(field.getValue())),
                mailboxIdFactory.fromString(mailboxId.getValue()),
                MessageUid.of(uidAsNumber.longValue())));
    } else {
        LOGGER.warn("Can not extract UID, MessageID and/or MailboxId for search result {}", hit.getId());
        return Flux.empty();
    }
}
 
Example 3
Source File: SearchQuestionBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private String origin(SearchHit hit){
    try {
        if ((hit.field("questionPoolId") != null) && (hit.field("questionPoolId").value()!=null)) {
            //First we check if we have the question pool title in the temporal cache
            if (qpTitlesCache.containsKey(hit.field("questionPoolId").value())){
                 return qpTitlesCache.get(hit.field("questionPoolId").value());
            }else {
                //If not... we retrieve the title and add it to the cache map.
                //We will do the same with the assessmentTitle and the siteTitle
                String qpTitle = questionPoolService.getPool(Long.parseLong(hit.field("questionPoolId").value()), AgentFacade.getAgentString()).getTitle();
                qpTitlesCache.put(hit.field("questionPoolId").value(),qpTitle);
                return qpTitle;
            }
        }else if ((hit.field("assessmentId") != null) && (hit.field("assessmentId").value() != null) && (hit.field("site") != null) && (hit.field("site").value() != null)) {
                String assessmentTitle="";
                String siteTitle="";
                if (assessmentTitlesCache.containsKey(hit.field("assessmentId").value())) {
                    assessmentTitle = assessmentTitlesCache.get(hit.field("assessmentId").value());
                }else{
                    assessmentTitle = assessmentService.getAssessment(hit.field("assessmentId").value().toString()).getTitle();
                    assessmentTitlesCache.put(hit.field("assessmentId").value(),assessmentTitle);
                }
                if (siteTitlesCache.containsKey(hit.field("site").value())) {
                    siteTitle = siteTitlesCache.get(hit.field("site").value());
                }else{
                    siteTitle = siteService.getSite(hit.field("site").value().toString()).getTitle();
                    siteTitlesCache.put(hit.field("site").value(),siteTitle);
                }

                return siteTitle + " : " + assessmentTitle;
        }else {
            return "";
        }
    }catch(Exception ex){
        //Maybe a question is orphan and has not assessment or question pool. In that case we just return empty string
        return "";
    }
}
 
Example 4
Source File: ProductQueryServiceImpl.java    From elasticsearch-tutorial with MIT License 5 votes vote down vote up
protected String getFieldValueOrNull(SearchHit searchHit, String fieldName)
{
    final SearchHitField searchHitField = searchHit.field(fieldName);
    if (searchHitField != null && searchHitField.value() != null) {
        return searchHitField.value().toString();
    }
    return null;
}
 
Example 5
Source File: ProductQueryServiceImpl.java    From elasticsearch-tutorial with MIT License 5 votes vote down vote up
protected Double getDoubleFieldValueOrNull(SearchHit searchHit, String fieldName)
{
    final SearchHitField searchHitField = searchHit.field(fieldName);
    if (searchHitField != null && searchHitField.value() != null) {
        return Double.valueOf(searchHitField.value().toString());
    }
    return null;
}
 
Example 6
Source File: ElasticsearchDataModel.java    From elasticsearch-taste with Apache License 2.0 5 votes vote down vote up
protected long getLongValue(final SearchHit hit, final String field) {
    final SearchHitField result = hit.field(field);
    if (result == null) {
        throw new TasteException(field + " is not found.");
    }
    final Number longValue = result.getValue();
    if (longValue == null) {
        throw new TasteException("The result of " + field + " is null.");
    }
    return longValue.longValue();
}
 
Example 7
Source File: ElasticsearchDataModel.java    From elasticsearch-taste with Apache License 2.0 5 votes vote down vote up
protected float getFloatValue(final SearchHit hit, final String field) {
    final SearchHitField result = hit.field(field);
    if (result == null) {
        throw new TasteException(field + " is not found.");
    }
    final Number floatValue = result.getValue();
    if (floatValue == null) {
        throw new TasteException("The result of " + field + " is null.");
    }
    return floatValue.floatValue();
}
 
Example 8
Source File: ProductQueryServiceImpl.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
protected String getFieldValueOrNull(final SearchHit searchHit,
		final String fieldName) {
	final SearchHitField searchHitField = searchHit.field(fieldName);
	if (searchHitField != null && searchHitField.value() != null) {
		return searchHitField.value().toString();
	}
	return null;
}
 
Example 9
Source File: ProductQueryServiceImpl.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
protected Double getDoubleFieldValueOrNull(final SearchHit searchHit,
		final String fieldName) {
	final SearchHitField searchHitField = searchHit.field(fieldName);
	if (searchHitField != null && searchHitField.value() != null) {
		return Double.valueOf(searchHitField.value().toString());
	}
	return null;
}
 
Example 10
Source File: SearchQuestionBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private String origin(SearchHit hit){
    try {
        if ((hit.field("questionPoolId") != null) && (hit.field("questionPoolId").value()!=null)) {
            //First we check if we have the question pool title in the temporal cache
            if (qpTitlesCache.containsKey(hit.field("questionPoolId").value())){
                 return qpTitlesCache.get(hit.field("questionPoolId").value());
            }else {
                //If not... we retrieve the title and add it to the cache map.
                //We will do the same with the assessmentTitle and the siteTitle
                String qpTitle = questionPoolService.getPool(Long.parseLong(hit.field("questionPoolId").value()), AgentFacade.getAgentString()).getTitle();
                qpTitlesCache.put(hit.field("questionPoolId").value(),qpTitle);
                return qpTitle;
            }
        }else if ((hit.field("assessmentId") != null) && (hit.field("assessmentId").value() != null) && (hit.field("site") != null) && (hit.field("site").value() != null)) {
                String assessmentTitle="";
                String siteTitle="";
                if (assessmentTitlesCache.containsKey(hit.field("assessmentId").value())) {
                    assessmentTitle = assessmentTitlesCache.get(hit.field("assessmentId").value());
                }else{
                    assessmentTitle = assessmentService.getAssessment(hit.field("assessmentId").value().toString()).getTitle();
                    assessmentTitlesCache.put(hit.field("assessmentId").value(),assessmentTitle);
                }
                if (siteTitlesCache.containsKey(hit.field("site").value())) {
                    siteTitle = siteTitlesCache.get(hit.field("site").value());
                }else{
                    siteTitle = siteService.getSite(hit.field("site").value().toString()).getTitle();
                    siteTitlesCache.put(hit.field("site").value(),siteTitle);
                }

                return siteTitle + " : " + assessmentTitle;
        }else {
            return "";
        }
    }catch(Exception ex){
        //Maybe a question is orphan and has not assessment or question pool. In that case we just return empty string
        return "";
    }
}
 
Example 11
Source File: GenTermValuesHandler.java    From elasticsearch-taste with Apache License 2.0 4 votes vote down vote up
@Override
public void onResponse(final SearchResponse response) {
    if (mTVListener != null) {
        try {
            mTVListener.await();
        } catch (final InterruptedException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Interrupted.", e);
            }
        }
    }

    if (interrupted) {
        return;
    }

    final SearchHits searchHits = response.getHits();
    final SearchHit[] hits = searchHits.getHits();
    if (hits.length == 0) {
        scrollSearchGate.countDown();
        shutdown();
    } else {
        final Map<String, DocInfo> idMap = new HashMap<>(hits.length);
        final MultiTermVectorsRequestBuilder requestBuilder = client
                .prepareMultiTermVectors();
        for (final SearchHit hit : hits) {
            final String id = hit.getId();
            final SearchHitField searchHitField = hit.field(idField);
            if (searchHitField != null) {
                idMap.put(id,
                        new DocInfo((String) searchHitField.getValue(),
                                hit.getSource()));
            }
            final TermVectorsRequest termVectorRequest = new TermVectorsRequest(
                    sourceIndex, sourceType, id);
            termVectorRequest.selectedFields(sourceFields);
            requestBuilder.add(termVectorRequest);
        }
        mTVListener = new MultiTermVectorsListener(numOfThreads,
                requestHandlers, eventParams, idMap, executor, logger);
        requestBuilder.execute(mTVListener);

        client.prepareSearchScroll(response.getScrollId())
                .setScroll(new TimeValue(keepAlive.longValue()))
                .execute(this);
    }
}
 
Example 12
Source File: TasteSearchRestAction.java    From elasticsearch-taste with Apache License 2.0 4 votes vote down vote up
@Override
protected void handleRequest(final RestRequest request,
        final RestChannel channel, final Client client) {

    final Info info = new Info(request);

    final String systemId = request.param("systemId");
    if (StringUtils.isBlank(systemId)) {
        onError(channel, new NotFoundException("No system_id."));
        return;
    }
    final String[] systemIds = systemId.trim().split(",");
    if (systemIds.length == 0) {
        onError(channel, new NotFoundException("No system_id."));
        return;
    }

    if (info.getIdIndex() == null) {
        onError(channel, new NotFoundException("No search type."));
        return;
    }

    final OnResponseListener<SearchResponse> responseListener = searchResponse -> {
        final SearchHits hits = searchResponse.getHits();
        if (hits.totalHits() == 0) {
            onError(channel,
                    new NotFoundException("No " + info.getIdField()
                            + " data for " + systemId + " in "
                            + info.getIdIndex() + "/" + info.getIdType()));
            return;
        }

        final SearchHit[] searchHits = hits.getHits();
        final long[] targetIds = new long[hits.getHits().length];
        for (int i = 0; i < targetIds.length && i < searchHits.length; i++) {
            final SearchHit hit = searchHits[i];
            final SearchHitField field = hit.field(info.getIdField());
            final Number targetId = field.getValue();
            if (targetId != null) {
                targetIds[i] = targetId.longValue();
            }
        }

        if (targetIds.length == 0) {
            onError(channel,
                    new NotFoundException("No " + info.getIdField()
                            + " for " + systemId + " in "
                            + info.getIdIndex() + "/" + info.getIdType()));
            return;
        }

        doSearchRequest(request, channel, client, info, targetIds);
    };

    final BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    for (final String id : systemIds) {
        boolQueryBuilder.should(QueryBuilders.termQuery("system_id", id));
    }
    boolQueryBuilder.minimumNumberShouldMatch(1);

    client.prepareSearch(info.getIdIndex()).setTypes(info.getIdType())
            .setQuery(boolQueryBuilder).addField(info.getIdField())
            .addSort(info.getTimestampField(), SortOrder.DESC)
            .setSize(systemIds.length)
            .execute(on(responseListener, t -> onError(channel, t)));

}