Java Code Examples for org.elasticsearch.action.search.SearchRequestBuilder#setFrom()

The following examples show how to use org.elasticsearch.action.search.SearchRequestBuilder#setFrom() . 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: TransportFeatureStoreAction.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a test search request to validate the element prior to storing it.
 *
 * @param validation validation info
 * @param element the element stored
 * @param task the parent task
 * @param listener the action listener to write to
 * @param onSuccess action ro run when the validation is successfull
 */
private void validate(FeatureValidation validation,
                      StorableElement element,
                      Task task,
                      ActionListener<FeatureStoreResponse> listener,
                      Runnable onSuccess) {
    ValidatingLtrQueryBuilder ltrBuilder = new ValidatingLtrQueryBuilder(element,
            validation, factory);
    SearchRequestBuilder builder = new SearchRequestBuilder(client, SearchAction.INSTANCE);
    builder.setIndices(validation.getIndex());
    builder.setQuery(ltrBuilder);
    builder.setFrom(0);
    builder.setSize(20);
    // Bail out early and don't score the whole index.
    builder.setTerminateAfter(1000);
    builder.request().setParentTask(clusterService.localNode().getId(), task.getId());
    builder.execute(wrap((r) -> {
            if (r.getFailedShards() > 0) {
                ShardSearchFailure failure = r.getShardFailures()[0];
                throw new IllegalArgumentException("Validating the element caused " + r.getFailedShards() +
                        " shard failures, see root cause: " + failure.reason(), failure.getCause());
            }
            onSuccess.run();
        },
        (e) -> listener.onFailure(new IllegalArgumentException("Cannot store element, validation failed.", e))));
}
 
Example 2
Source File: ClientFacade.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private SearchRequestBuilder createSearchRequest(
    QueryBuilder query,
    Integer from,
    Integer size,
    Sort sort,
    List<AggregationBuilder> aggregations,
    List<Index> indexes) {
  String[] indexNames = toIndexNames(indexes);
  SearchRequestBuilder searchRequest = client.prepareSearch(indexNames);
  if (query != null) {
    searchRequest.setQuery(query);
  }
  if (from != null) {
    searchRequest.setFrom(from);
  }
  if (size != null) {
    searchRequest.setSize(size);
  }
  if (sort != null) {
    List<SortBuilder> sorts = sortContentBuilder.createSorts(sort);
    sorts.forEach(searchRequest::addSort);
  }
  if (aggregations != null) {
    aggregations.forEach(searchRequest::addAggregation);
  }
  return searchRequest;
}
 
Example 3
Source File: ElasticSearchFinder.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public Stream<EntityReference> findEntities( Class<?> resultType,
                                             Predicate<Composite> whereClause,
                                             List<OrderBy> orderBySegments,
                                             Integer firstResult,
                                             Integer maxResults,
                                             Map<String, Object> variables ) throws EntityFinderException
{
    // Prepare request
    SearchRequestBuilder request = support.client().prepareSearch( support.index() );

    BoolQueryBuilder baseQueryBuilder = baseQuery( resultType );
    QueryBuilder whereQueryBuilder = processWhereSpecification( baseQueryBuilder, whereClause, variables );

    request.setQuery( boolQuery().must( whereQueryBuilder ).filter( baseQueryBuilder ) );
    if( firstResult != null )
    {
        request.setFrom( firstResult );
    }
    if( maxResults != null )
    {
        request.setSize( maxResults );
    }
    else
    {
        //request.setSize( Integer.MAX_VALUE ); // TODO Use scrolls?
    }
    if( orderBySegments != null )
    {
        for( OrderBy order : orderBySegments )
        {
            request.addSort( order.property().toString(),
                             order.order() == OrderBy.Order.ASCENDING ? SortOrder.ASC : SortOrder.DESC );
        }
    }

    // Log
    LOGGER.debug( "Will search Entities: {}", request );

    // Execute
    SearchResponse response = request.execute().actionGet();

    return StreamSupport.stream( response.getHits().spliterator(), false )
                        .map( hit -> EntityReference.parseEntityReference( hit.getId() ) );
}
 
Example 4
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 4 votes vote down vote up
@Override
protected <RESULT extends ENTITY> List<RESULT> delegateSelectList(final ConditionBean cb, final Class<? extends RESULT> entityType) {
    // #pending check response
    final SearchRequestBuilder builder = client.prepareSearch(asEsIndex());
    final int from;
    final int size;
    if (cb.isFetchScopeEffective()) {
        from = cb.getPageStartIndex();
        size = cb.getFetchSize();
    } else {
        from = 0;
        size = 10;
    }
    builder.setFrom(from);
    builder.setSize(size);
    final EsAbstractConditionBean esCb = (EsAbstractConditionBean) cb;
    if (esCb.getPreference() != null) {
        builder.setPreference(esCb.getPreference());
    }
    esCb.request().build(builder);
    final SearchResponse response = esCb.build(builder).execute().actionGet(searchTimeout);

    final EsPagingResultBean<RESULT> list = new EsPagingResultBean<>(builder);
    final SearchHits searchHits = getSearchHits(response);
    searchHits.forEach(hit -> {
        final Map<String, Object> source = hit.getSourceAsMap();
        final RESULT entity = createEntity(source, entityType);
        final DocMeta docMeta = ((EsAbstractEntity) entity).asDocMeta();
        docMeta.id(hit.getId());
        docMeta.version(hit.getVersion());
        docMeta.seqNo(hit.getSeqNo());
        docMeta.primaryTerm(hit.getPrimaryTerm());
        list.add(entity);
    });

    list.setPageSize(size);
    list.setAllRecordCount((int) searchHits.getTotalHits().value);
    list.setCurrentPageNumber(cb.getFetchPageNumber());

    list.setTook(response.getTook().getMillis());
    list.setTotalShards(response.getTotalShards());
    list.setSuccessfulShards(response.getSuccessfulShards());
    list.setFailedShards(response.getFailedShards());
    list.setTotalHits(searchHits.getTotalHits());

    list.setAggregation(response.getAggregations());

    // #pending others

    return list;
}
 
Example 5
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 4 votes vote down vote up
@Override
protected <RESULT extends ENTITY> List<RESULT> delegateSelectList(final ConditionBean cb, final Class<? extends RESULT> entityType) {
    // #pending check response
    final SearchRequestBuilder builder = client.prepareSearch(asEsIndex());
    final int from;
    final int size;
    if (cb.isFetchScopeEffective()) {
        from = cb.getPageStartIndex();
        size = cb.getFetchSize();
    } else {
        from = 0;
        size = 10;
    }
    builder.setFrom(from);
    builder.setSize(size);
    final EsAbstractConditionBean esCb = (EsAbstractConditionBean) cb;
    if (esCb.getPreference() != null) {
        builder.setPreference(esCb.getPreference());
    }
    esCb.request().build(builder);
    final SearchResponse response = esCb.build(builder).execute().actionGet(searchTimeout);

    final EsPagingResultBean<RESULT> list = new EsPagingResultBean<>(builder);
    final SearchHits searchHits = getSearchHits(response);
    searchHits.forEach(hit -> {
        final Map<String, Object> source = hit.getSourceAsMap();
        final RESULT entity = createEntity(source, entityType);
        final DocMeta docMeta = ((EsAbstractEntity) entity).asDocMeta();
        docMeta.id(hit.getId());
        docMeta.version(hit.getVersion());
        docMeta.seqNo(hit.getSeqNo());
        docMeta.primaryTerm(hit.getPrimaryTerm());
        list.add(entity);
    });

    list.setPageSize(size);
    list.setAllRecordCount((int) searchHits.getTotalHits().value);
    list.setCurrentPageNumber(cb.getFetchPageNumber());

    list.setTook(response.getTook().getMillis());
    list.setTotalShards(response.getTotalShards());
    list.setSuccessfulShards(response.getSuccessfulShards());
    list.setFailedShards(response.getFailedShards());
    list.setTotalHits(searchHits.getTotalHits());

    list.setAggregation(response.getAggregations());

    // #pending others

    return list;
}
 
Example 6
Source File: EsAbstractBehavior.java    From fess with Apache License 2.0 4 votes vote down vote up
@Override
protected <RESULT extends ENTITY> List<RESULT> delegateSelectList(final ConditionBean cb, final Class<? extends RESULT> entityType) {
    // #pending check response
    final SearchRequestBuilder builder = client.prepareSearch(asEsIndex());
    final int from;
    final int size;
    if (cb.isFetchScopeEffective()) {
        from = cb.getPageStartIndex();
        size = cb.getFetchSize();
    } else {
        from = 0;
        size = 10;
    }
    builder.setFrom(from);
    builder.setSize(size);
    final EsAbstractConditionBean esCb = (EsAbstractConditionBean) cb;
    if (esCb.getPreference() != null) {
        builder.setPreference(esCb.getPreference());
    }
    esCb.request().build(builder);
    final SearchResponse response = esCb.build(builder).execute().actionGet(searchTimeout);

    final EsPagingResultBean<RESULT> list = new EsPagingResultBean<>(builder);
    final SearchHits searchHits = getSearchHits(response);
    searchHits.forEach(hit -> {
        final Map<String, Object> source = hit.getSourceAsMap();
        final RESULT entity = createEntity(source, entityType);
        final DocMeta docMeta = ((EsAbstractEntity) entity).asDocMeta();
        docMeta.id(hit.getId());
        docMeta.version(hit.getVersion());
        docMeta.seqNo(hit.getSeqNo());
        docMeta.primaryTerm(hit.getPrimaryTerm());
        list.add(entity);
    });

    list.setPageSize(size);
    list.setAllRecordCount((int) searchHits.getTotalHits().value);
    list.setCurrentPageNumber(cb.getFetchPageNumber());

    list.setTook(response.getTook().getMillis());
    list.setTotalShards(response.getTotalShards());
    list.setSuccessfulShards(response.getSuccessfulShards());
    list.setFailedShards(response.getFailedShards());
    list.setTotalHits(searchHits.getTotalHits());

    list.setAggregation(response.getAggregations());

    // #pending others

    return list;
}