Java Code Examples for org.elasticsearch.search.sort.SortOrder#ASC

The following examples show how to use org.elasticsearch.search.sort.SortOrder#ASC . 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: QueryOrderByParser.java    From elasticsearch-sql with MIT License 7 votes vote down vote up
@Override
public void parse(ElasticDslContext dslContext) {
    if(dslContext.getSqlContext().selectOperation()!=null&&dslContext.getSqlContext().selectOperation().groupByClause()==null){
        if(dslContext.getSqlContext().selectOperation().orderClause()!=null){
            ElasticsearchParser.OrderClauseContext orderClauseContext=dslContext.getSqlContext().selectOperation().orderClause();
            for(ElasticsearchParser.OrderContext orderContext:orderClauseContext.order()){
                ElasticsearchParser.NameClauseContext nameContext = orderContext.nameClause();
                if(nameContext instanceof ElasticsearchParser.FieldNameContext){
                    ElasticsearchParser.FieldNameContext fieldNameContext=(ElasticsearchParser.FieldNameContext)nameContext;
                    String field = fieldNameContext.field.getText();
                    if(fieldNameContext.highlighter!=null){
                        dslContext.getParseResult().getHighlighter().add(field);
                    }
                    SortOrder sortOrder;
                    if(orderContext.ASC()!=null) {
                        sortOrder=SortOrder.ASC;
                    }else{
                        sortOrder=SortOrder.DESC;
                    }
                    SortBuilder sortBuilder = SortBuilders.fieldSort(field).sortMode(SortMode.AVG).order(sortOrder);
                    dslContext.getParseResult().getOrderBy().add(sortBuilder);
                }
            }
        }
    }
}
 
Example 2
Source File: SearchUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private SortOrder getValidSortOrder(String direction, SortOrder defaultValue) {
  if (direction != null) {
    switch (direction.toLowerCase()) {
      case "asc":
      case "ascending":
        return SortOrder.ASC;
      case "desc":
      case "descending":
        return SortOrder.DESC;
      default:
        break;
    }
  }

  return defaultValue;
}
 
Example 3
Source File: Sort.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Sort(String description) {
    this();
    if (description.startsWith("date:")) {
        this.option = Option.DATE;
        description = description.substring(5);
        if (description.startsWith("A")) {
            this.direction = SortOrder.ASC;
        } else {
            this.direction = SortOrder.DESC;
        }
    }
    if (description.startsWith("meta:")) {
        this.option = Option.METADATA;
        description = description.substring(5);
        int p = description.indexOf(':');
        if (p >= 0) {
            this.metafield = description.substring(0, p);
            description = description.substring(p + 1);
            if (description.startsWith("A")) {
                this.direction = SortOrder.ASC;
            } else {
                this.direction = SortOrder.DESC;
            }
        }
    }
}
 
Example 4
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find object ids for a given query in an index.
 *
 * @param indexName The name of the index.
 * @param queryBuilder The query to use for searching.
 * @param start The start to use.
 * @param size The total return size.
 * @param sortOptions A list of string options to sort in the form VALUE:ORDER; where ORDER is optional and can be either ASC OR DESC.
 * @param docType The document type to searchObjectIdsViaExpression for.
 *
 * @return The SearchResults which includes the count and IDs that were found.
 * @throws IOException If we cannot communicate with ES.
 */
private SearchResult<String> searchObjectIds(String indexName, QueryBuilder queryBuilder, int start, int size, List<String> sortOptions, String docType) throws IOException {

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(queryBuilder);
    searchSourceBuilder.from(start);
    searchSourceBuilder.size(size);

    if (sortOptions != null && !sortOptions.isEmpty()) {

        for (String sortOption : sortOptions) {
            SortOrder order = SortOrder.ASC;
            String field = sortOption;
            int index = sortOption.indexOf(":");
            if (index > 0) {
                field = sortOption.substring(0, index);
                order = SortOrder.valueOf(sortOption.substring(index + 1));
            }
            searchSourceBuilder.sort(new FieldSortBuilder(field).order(order));
        }
    }

    // Generate the actual request to send to ES.
    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.types(docType);
    searchRequest.source(searchSourceBuilder);

    SearchResponse response = elasticSearchClient.search(searchRequest);

    List<String> result = new LinkedList<>();
    response.getHits().forEach(hit -> result.add(hit.getId()));
    long count = response.getHits().getTotalHits();
    return new SearchResult<>(count, result);
}
 
Example 5
Source File: SortConverter.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static SortOrder getOrder(SearchQuery.Sort sort) {
    if (sort.isReverse()) {
        return SortOrder.DESC;
    } else {
        return SortOrder.ASC;
    }
}
 
Example 6
Source File: ElasticsearchLengthOfStringSortingStrategy.java    From vertexium with Apache License 2.0 5 votes vote down vote up
@Override
public void updateElasticsearchQuery(
    Graph graph,
    Elasticsearch5SearchIndex searchIndex,
    SearchRequestBuilder q,
    QueryParameters parameters,
    SortDirection direction
) {
    PropertyDefinition propertyDefinition = graph.getPropertyDefinition(getPropertyName());

    SortOrder esOrder = direction == SortDirection.ASCENDING ? SortOrder.ASC : SortOrder.DESC;
    Map<String, Object> scriptParams = new HashMap<>();
    String[] propertyNames = searchIndex.getPropertyNames(graph, getPropertyName(), parameters.getAuthorizations());
    List<String> fieldNames = Arrays.stream(propertyNames)
        .map(propertyName -> {
            String suffix = propertyDefinition.getDataType() == String.class
                ? Elasticsearch5SearchIndex.EXACT_MATCH_PROPERTY_NAME_SUFFIX
                : "";
            return propertyName + suffix;
        })
        .collect(Collectors.toList());
    scriptParams.put("fieldNames", fieldNames);
    scriptParams.put("direction", esOrder.name());
    Script script = new Script(ScriptType.INLINE, "painless", scriptSource, scriptParams);
    ScriptSortBuilder.ScriptSortType sortType = ScriptSortBuilder.ScriptSortType.NUMBER;
    q.addSort(SortBuilders.scriptSort(script, sortType).order(SortOrder.ASC));
}
 
Example 7
Source File: ElasticsearchLengthOfStringSortingStrategy.java    From vertexium with Apache License 2.0 5 votes vote down vote up
@Override
public void updateElasticsearchQuery(
    Graph graph,
    Elasticsearch7SearchIndex searchIndex,
    SearchRequestBuilder q,
    QueryParameters parameters,
    SortDirection direction
) {
    PropertyDefinition propertyDefinition = graph.getPropertyDefinition(getPropertyName());

    SortOrder esOrder = direction == SortDirection.ASCENDING ? SortOrder.ASC : SortOrder.DESC;
    Map<String, Object> scriptParams = new HashMap<>();
    String[] propertyNames = searchIndex.getPropertyNames(graph, getPropertyName(), parameters.getAuthorizations());
    List<String> fieldNames = Arrays.stream(propertyNames)
        .map(propertyName -> {
            String suffix = propertyDefinition.getDataType() == String.class
                ? Elasticsearch7SearchIndex.EXACT_MATCH_PROPERTY_NAME_SUFFIX
                : "";
            return propertyName + suffix;
        })
        .collect(Collectors.toList());
    scriptParams.put("fieldNames", fieldNames);
    scriptParams.put("direction", esOrder.name());
    Script script = new Script(ScriptType.INLINE, "painless", scriptSource, scriptParams);
    ScriptSortBuilder.ScriptSortType sortType = ScriptSortBuilder.ScriptSortType.NUMBER;
    q.addSort(SortBuilders.scriptSort(script, sortType).order(SortOrder.ASC));
}
 
Example 8
Source File: ElasticSearchRestDAOV6.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find object ids for a given query in an index.
 *
 * @param indexName    The name of the index.
 * @param queryBuilder The query to use for searching.
 * @param start        The start to use.
 * @param size         The total return size.
 * @param sortOptions  A list of string options to sort in the form VALUE:ORDER; where ORDER is optional and can be
 *                     either ASC OR DESC.
 * @param docType      The document type to searchObjectIdsViaExpression for.
 * @return The SearchResults which includes the count and IDs that were found.
 * @throws IOException If we cannot communicate with ES.
 */
private SearchResult<String> searchObjectIds(String indexName, QueryBuilder queryBuilder, int start, int size,
    List<String> sortOptions, String docType) throws IOException {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(queryBuilder);
    searchSourceBuilder.from(start);
    searchSourceBuilder.size(size);

    if (sortOptions != null && !sortOptions.isEmpty()) {

        for (String sortOption : sortOptions) {
            SortOrder order = SortOrder.ASC;
            String field = sortOption;
            int index = sortOption.indexOf(":");
            if (index > 0) {
                field = sortOption.substring(0, index);
                order = SortOrder.valueOf(sortOption.substring(index + 1));
            }
            searchSourceBuilder.sort(new FieldSortBuilder(field).order(order));
        }
    }

    // Generate the actual request to send to ES.
    docType = StringUtils.isBlank(docTypeOverride) ? docType : docTypeOverride;
    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.types(docType);
    searchRequest.source(searchSourceBuilder);

    SearchResponse response = elasticSearchClient.search(searchRequest);

    List<String> result = new LinkedList<>();
    response.getHits().forEach(hit -> result.add(hit.getId()));
    long count = response.getHits().getTotalHits();
    return new SearchResult<>(count, result);
}
 
Example 9
Source File: TestElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find object ids for a given query in an index.
 *
 * @param indexName The name of the index.
 * @param queryBuilder The query to use for searching.
 * @param start The start to use.
 * @param size The total return size.
 * @param sortOptions A list of string options to sort in the form VALUE:ORDER; where ORDER is optional and can be either ASC OR DESC.
 * @param docType The document type to searchObjectIdsViaExpression for.
 *
 * @return The SearchResults which includes the count and IDs that were found.
 * @throws IOException If we cannot communicate with ES.
 */
private SearchResponse searchObjectIds(String indexName, QueryBuilder queryBuilder, int start, int size, List<String> sortOptions, String docType) throws IOException {

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(queryBuilder);
    searchSourceBuilder.from(start);
    searchSourceBuilder.size(size);

    if (sortOptions != null && !sortOptions.isEmpty()) {

        for (String sortOption : sortOptions) {
            SortOrder order = SortOrder.ASC;
            String field = sortOption;
            int index = sortOption.indexOf(":");
            if (index > 0) {
                field = sortOption.substring(0, index);
                order = SortOrder.valueOf(sortOption.substring(index + 1));
            }
            searchSourceBuilder.sort(new FieldSortBuilder(field).order(order));
        }
    }

    // Generate the actual request to send to ES.
    SearchRequest searchRequest = new SearchRequest(indexName);
    searchRequest.types(docType);
    searchRequest.source(searchSourceBuilder);

    return elasticSearchClient.search(searchRequest);
}
 
Example 10
Source File: ElasticsearchSort.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
public void implement(Implementor implementor) {
    implementor.visitChild(0, getInput());
    ElasticsearchTable esTable = implementor.getElasticsearchTable();
    List<RelFieldCollation> fieldCollations = collation.getFieldCollations();
    if(fieldCollations != null)
    {
        List<RelDataTypeField> fieldList = esTable.getRowType().getFieldList();
        for(RelFieldCollation fieldCollation : fieldCollations) {
            SortOrder order = SortOrder.ASC;
            esTable.setIsSort(true);
            esTable.setIsAsc(true);
            switch (fieldCollation.getDirection())
            {
                case DESCENDING:
                case STRICTLY_DESCENDING:
                    order = SortOrder.DESC;
                    esTable.setIsAsc(false);
            }
            esTable.addSortBuilder(esTable.transFieldName(fieldList.get(fieldCollation.getFieldIndex()).getName().toLowerCase(),fieldList), order);
        }
    }

    if(offset != null && offset instanceof RexLiteral)
        esTable.setSearchOffset(Integer.parseInt(((RexLiteral) offset).getValue2().toString()));
    if(fetch != null && fetch instanceof RexLiteral)
        esTable.setSearchSize(Integer.parseInt(((RexLiteral) fetch).getValue2().toString()));
}
 
Example 11
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
private void addSortOptionToSearchRequest(SearchRequestBuilder searchRequestBuilder,
    String sortOption) {
    SortOrder order = SortOrder.ASC;
    String field = sortOption;
    int indx = sortOption.indexOf(':');
    if (indx > 0) {    // Can't be 0, need the field name at-least
        field = sortOption.substring(0, indx);
        order = SortOrder.valueOf(sortOption.substring(indx + 1));
    }
    searchRequestBuilder.addSort(field, order);
}
 
Example 12
Source File: ElasticsearchRepository.java    From staccato with Apache License 2.0 5 votes vote down vote up
protected void configureSort(SearchSourceBuilder searchSourceBuilder, SortExtension sort) {
    if (sort == null || sort.isEmpty()) {
        searchSourceBuilder
                .sort(new FieldSortBuilder("properties.datetime").order(SortOrder.DESC))
                .sort(new FieldSortBuilder("id").order(SortOrder.ASC));
        return;
    }

    for (SortExtension.SortTerm term : sort) {
        SortOrder sortOrder = (term.getDirection() == SortExtension.SortTerm.SortDirection.DESC) ?
                SortOrder.DESC : SortOrder.ASC;
        searchSourceBuilder.sort(new FieldSortBuilder(term.getField()).order(sortOrder));
    }
    searchSourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.DESC));
}
 
Example 13
Source File: ElasticsearchSort.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
public void implement(Implementor implementor) {
    implementor.visitChild(0, getInput());
    ElasticsearchTable esTable = implementor.getElasticsearchTable();
    List<RelFieldCollation> fieldCollations = collation.getFieldCollations();
    if(fieldCollations != null)
    {
        List<RelDataTypeField> fieldList = esTable.getRowType().getFieldList();
        for(RelFieldCollation fieldCollation : fieldCollations) {
            SortOrder order = SortOrder.ASC;
            esTable.setIsSort(true);
            esTable.setIsAsc(true);
            switch (fieldCollation.getDirection())
            {
                case DESCENDING:
                case STRICTLY_DESCENDING:
                    order = SortOrder.DESC;
                    esTable.setIsAsc(false);
            }
            esTable.addSortBuilder(esTable.transFieldName(fieldList.get(fieldCollation.getFieldIndex()).getName().toLowerCase(),fieldList), order);
        }
    }

    if(offset != null && offset instanceof RexLiteral)
        esTable.setSearchOffset(Integer.parseInt(((RexLiteral) offset).getValue2().toString()));
    if(fetch != null && fetch instanceof RexLiteral)
        esTable.setSearchSize(Integer.parseInt(((RexLiteral) fetch).getValue2().toString()));
}
 
Example 14
Source File: ElasticSearchHelper.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/** Method to return the sorting order on basis of string param . */
public static SortOrder getSortOrder(String value) {
  return ASC_ORDER.equalsIgnoreCase(value) ? SortOrder.ASC : SortOrder.DESC;
}
 
Example 15
Source File: OrderBy.java    From sql4es with Apache License 2.0 4 votes vote down vote up
public int func(){
	if(order == SortOrder.ASC) return 1;
	else return -1;
}
 
Example 16
Source File: OrderByParser.java    From sql4es with Apache License 2.0 4 votes vote down vote up
@Override
protected OrderBy visitSortItem(SortItem si, QueryState state){
	String orderKey = null;
	if(si.getSortKey() instanceof DereferenceExpression){
		orderKey = SelectParser.visitDereferenceExpression((DereferenceExpression)si.getSortKey());
	}else if (si.getSortKey() instanceof FunctionCall){
		orderKey = si.getSortKey().toString().replaceAll("\"","");
	}else if(si.getSortKey() instanceof SearchedCaseExpression){
		//... order by CASE WHEN field IS NULL THEN 1 ELSE 0 END
		// TODO: improve this quick and dirty implementation
		SearchedCaseExpression sce = (SearchedCaseExpression)si.getSortKey();
		for(WhenClause when : sce.getWhenClauses()){
			orderKey = SelectParser.visitDereferenceExpression(
					(DereferenceExpression)((IsNullPredicate)when.getOperand()).getValue());
		}
	}else if(si.getSortKey() instanceof Identifier){
		orderKey = ((Identifier)si.getSortKey()).getName(); //.getValue();
	}else {
		state.addException("Order statement with type '"+si.getSortKey().getClass().getName()+"' is not supported");
		return null;
	}
	// fix case
	orderKey = Heading.findOriginal(state.originalSql()+";", orderKey, "order by.+", "\\W");
	// remove any table reference or alias
	if(orderKey.contains(".")){
		String prefix = orderKey.split("\\.")[0];
		for(QuerySource tr : state.getSources()){
			if(tr.getAlias() != null){
				if(prefix.equals(tr.getAlias())) orderKey = orderKey.substring(orderKey.indexOf('.')+1);
			}else if (tr.getSource() != null && prefix.equals(tr.getSource())) orderKey = orderKey.substring(orderKey.indexOf('.')+1);
		}
	}
	// select column to order on
	Column column = state.getHeading().getColumnByLabel(orderKey);
	if(column != null){
		if(si.getOrdering().toString().startsWith("ASC")){
			return new OrderBy(column.getColumn(), SortOrder.ASC, column.getIndex());
		}else{
			return new OrderBy(column.getColumn(), SortOrder.DESC, column.getIndex());
		}
	}else{
		state.addException("Order key '"+orderKey+"' is not specified in SELECT clause");
		return null;
	}
}
 
Example 17
Source File: EsUtil.java    From java-study with Apache License 2.0 4 votes vote down vote up
/**
 * @return boolean
 * @Author pancm
 * @Description 根据条件查询
 * @Date 2019/3/21
 * @Param []
 **/
public static List<Map<String, Object>> query(String index, String type, EsQueryCondition esQueryCondition, QueryBuilder... queryBuilders) throws IOException {
    if (index == null || type == null) {
        return null;
    }
    List<Map<String, Object>> list = new ArrayList<>();
    try {
        // 查询指定的索引库
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.types(type);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        if (esQueryCondition != null) {
            Integer form = esQueryCondition.getIndex();
            Integer pagesize = esQueryCondition.getPagesize();
            if (form != null && form > 0 && pagesize != null && pagesize > 0) {
                form = (form - 1) * pagesize;
                pagesize = form + pagesize;
                // 设置起止和结束
                sourceBuilder.from(form);
                sourceBuilder.size(pagesize);
            }
            String routing = esQueryCondition.getRouting();
            if (routing != null && routing.length() > 0) {
                // 设置路由
                searchRequest.routing(routing);
            }

            // 设置索引库表达式
            searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen());

            //设置排序
            String order = esQueryCondition.getOrder();
            if (order != null) {
                String[] orderField = esQueryCondition.getOrderField();
                SortOrder order2 = order.equals(SortOrder.DESC) ? SortOrder.DESC : SortOrder.ASC;
                //如果设置了排序字段则用排序的字段进行排序,否则就默认排序
                if (orderField != null) {
                    for (String field : orderField) {
                        sourceBuilder.sort(new FieldSortBuilder(field).order(order2));
                    }
                } else {
                    sourceBuilder.sort(new ScoreSortBuilder().order(order2));
                }
            }
            String[] includeFields = esQueryCondition.getIncludeFields();
            String[] excludeFields = esQueryCondition.getExcludeFields();
            if (includeFields != null && includeFields.length > 0 && excludeFields != null && excludeFields.length > 0) {
                sourceBuilder.fetchSource(includeFields, excludeFields);
            }
            sourceBuilder.fetchSource(esQueryCondition.isCloseSource());
        }
        //设置条件
        if (queryBuilders != null) {
            for (QueryBuilder queryBuilder : queryBuilders) {
                sourceBuilder.query(queryBuilder);
            }
        }

        searchRequest.source(sourceBuilder);
        // 同步查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        if(queryBuilders != null|| (esQueryCondition != null && esQueryCondition.isQueryData())){
            // 结果
            searchResponse.getHits().forEach(hit -> {
                Map<String, Object> map = hit.getSourceAsMap();
                list.add(map);
            });
        }

          if(esQueryCondition != null && esQueryCondition.isNeedTotal()){
              Map<String, Object> mapTotal = new HashMap<>();
              mapTotal.put("total", searchResponse.getHits().getTotalHits());
              list.add(mapTotal);
          }

    } finally {
        if (isAutoClose) {
            close();
        }
    }
    return list;
}
 
Example 18
Source File: EsSearchRequest.java    From mall with Apache License 2.0 4 votes vote down vote up
public SortOrder getOrder() {
    return order == 1 ? SortOrder.DESC : SortOrder.ASC;
}