org.elasticsearch.search.sort.ScriptSortBuilder Java Examples

The following examples show how to use org.elasticsearch.search.sort.ScriptSortBuilder. 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: ElasticSearchIntegrationTest.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
@Test
void search() {
    TestDocument document = document("1", "1st Test's Product", 1, 0, null, LocalTime.NOON);
    documentType.index(document.id, document);
    elasticSearch.refreshIndex("document");

    // test synonyms
    SearchRequest request = new SearchRequest();
    request.query = boolQuery()
        .must(matchQuery("string_field", "first"))
        .filter(termQuery("enum_field", JSON.toEnumValue(TestDocument.TestEnum.VALUE1)));
    request.sorts.add(SortBuilders.scriptSort(new Script("doc['int_field'].value * 3"), ScriptSortBuilder.ScriptSortType.NUMBER));
    SearchResponse<TestDocument> response = documentType.search(request);

    assertThat(response.totalHits).isEqualTo(1);
    assertThat(response.hits.get(0)).isEqualToIgnoringGivenFields(document, "zonedDateTimeField");

    // test stemmer
    request = new SearchRequest();
    request.query = matchQuery("string_field", "test");
    response = documentType.search(request);

    assertThat(response.totalHits).isEqualTo(1);
    assertThat(response.hits.get(0)).isEqualToIgnoringGivenFields(document, "zonedDateTimeField");
}
 
Example #2
Source File: DefaultQueryAction.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
/**
 * Add sorts to the elasticsearch query based on the 'ORDER BY' clause.
 * 
 * @param orderBys
 *            list of Order object
 */
private void setSorts(List<Order> orderBys) {
	for (Order order : orderBys) {
           if (order.getNestedPath() != null) {
               request.addSort(SortBuilders.fieldSort(order.getName()).order(SortOrder.valueOf(order.getType())).setNestedSort(new NestedSortBuilder(order.getNestedPath())));
           } else if (order.getName().contains("script(")) { //zhongshu-comment 该分支是我后来加的,用于兼容order by case when那种情况

			String scriptStr = order.getName().substring("script(".length(), order.getName().length() - 1);
			Script script = new Script(scriptStr);
			ScriptSortBuilder scriptSortBuilder = SortBuilders.scriptSort(script, order.getScriptSortType());

			scriptSortBuilder = scriptSortBuilder.order(SortOrder.valueOf(order.getType()));
			request.addSort(scriptSortBuilder);
		} else {
               request.addSort(
               		order.getName(),
					SortOrder.valueOf(order.getType()));
           }
	}
}
 
Example #3
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
private void addOrderByToSelect(Select select, List<SQLSelectOrderByItem> items, String alias) throws SqlParseException {
    for (SQLSelectOrderByItem sqlSelectOrderByItem : items) {
        SQLExpr expr = sqlSelectOrderByItem.getExpr();
        Field f = FieldMaker.makeField(expr, null, null);
        String orderByName = f.toString();

        if (sqlSelectOrderByItem.getType() == null) {
            sqlSelectOrderByItem.setType(SQLOrderingSpecification.ASC); //zhongshu-comment 默认是升序排序
        }
        String type = sqlSelectOrderByItem.getType().toString();

        orderByName = orderByName.replace("`", "");
        if (alias != null) orderByName = orderByName.replaceFirst(alias + "\\.", "");

        ScriptSortBuilder.ScriptSortType scriptSortType = judgeIsStringSort(expr);
        select.addOrderBy(f.getNestedPath(), orderByName, type, scriptSortType);
    }
}
 
Example #4
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 #5
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 #6
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private ScriptSortBuilder.ScriptSortType judgeIsStringSort(SQLExpr expr) {
    if (expr instanceof SQLCaseExpr) {
        List<SQLCaseExpr.Item> itemList = ((SQLCaseExpr) expr).getItems();
        for (SQLCaseExpr.Item item : itemList) {
            if (item.getValueExpr() instanceof SQLCharExpr) {
                return ScriptSortBuilder.ScriptSortType.STRING;
            }
        }
    }
    return ScriptSortBuilder.ScriptSortType.NUMBER;
}
 
Example #7
Source File: Select.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public void addOrderBy(String nestedPath, String name, String type, ScriptSortBuilder.ScriptSortType scriptSortType) {
	if ("_score".equals(name)) { //zhongshu-comment 可以直接在order by子句中写_score,根据该字段排序 select * from tbl order by _score asc
		isQuery = true;
	}
	Order order = new Order(nestedPath, name, type);

	order.setScriptSortType(scriptSortType);
	this.orderBys.add(order);
}
 
Example #8
Source File: Order.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public ScriptSortBuilder.ScriptSortType getScriptSortType() {
	return scriptSortType;
}
 
Example #9
Source File: Order.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public void setScriptSortType(ScriptSortBuilder.ScriptSortType scriptSortType) {
	this.scriptSortType = scriptSortType;
}