Java Code Examples for org.elasticsearch.script.ScriptType#INLINE

The following examples show how to use org.elasticsearch.script.ScriptType#INLINE . 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: IndexSearchDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Processes the scripts and score function
 *
 * @param queryBuilder the query builder
 *
 * @return the function score query builder
 */
private FunctionScoreQueryBuilder getFunctionScoreQueryBuilder(QueryBuilder queryBuilder, String bdefActiveIndex)
{
    // Script for tag search score multiplier. If bdef set to tag search score multiplier else set to a default value.
    String inlineScript = "_score * (doc['_index'].value == '" + bdefActiveIndex + "' ? doc['" + BDEF_TAGS_SEARCH_SCORE_MULTIPLIER + "'].value : 1)";

    // Set the lang to painless
    Script script = new Script(ScriptType.INLINE, "painless", inlineScript, Collections.emptyMap());

    // Set the script
    ScriptScoreFunctionBuilder scoreFunction = ScoreFunctionBuilders.scriptFunction(script);

    // Create function score query builder
    return new FunctionScoreQueryBuilder(queryBuilder, scoreFunction);
}
 
Example 2
Source File: ElasticsearchHammingDistanceScoringStrategy.java    From vertexium with Apache License 2.0 6 votes vote down vote up
@Override
public QueryBuilder updateElasticsearchQuery(
    Graph graph,
    Elasticsearch5SearchIndex searchIndex,
    QueryBuilder query,
    QueryParameters queryParameters
) {
    List<String> fieldNames = getFieldNames(graph, searchIndex, queryParameters, getField());
    if (fieldNames == null) {
        return query;
    }

    HashMap<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("hash", getHash());
    scriptParams.put("fieldNames", fieldNames);
    Script script = new Script(ScriptType.INLINE, "painless", scriptSrc, scriptParams);
    return QueryBuilders.functionScoreQuery(query, new ScriptScoreFunctionBuilder(script));
}
 
Example 3
Source File: ElasticsearchFieldValueScoringStrategy.java    From vertexium with Apache License 2.0 6 votes vote down vote up
@Override
public QueryBuilder updateElasticsearchQuery(
    Graph graph,
    Elasticsearch5SearchIndex searchIndex,
    QueryBuilder query,
    QueryParameters queryParameters
) {
    List<String> fieldNames = getFieldNames(graph, searchIndex, queryParameters, getField());
    if (fieldNames == null) {
        return query;
    }

    HashMap<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("fieldNames", fieldNames);
    Script script = new Script(ScriptType.INLINE, "painless", scriptSrc, scriptParams);
    return QueryBuilders.functionScoreQuery(query, new ScriptScoreFunctionBuilder(script));
}
 
Example 4
Source File: ElasticsearchHammingDistanceScoringStrategy.java    From vertexium with Apache License 2.0 6 votes vote down vote up
@Override
public QueryBuilder updateElasticsearchQuery(
    Graph graph,
    Elasticsearch7SearchIndex searchIndex,
    QueryBuilder query,
    QueryParameters queryParameters
) {
    List<String> fieldNames = getFieldNames(graph, searchIndex, queryParameters, getField());
    if (fieldNames == null) {
        return query;
    }

    HashMap<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("hash", getHash());
    scriptParams.put("fieldNames", fieldNames);
    Script script = new Script(ScriptType.INLINE, "painless", scriptSrc, scriptParams);
    return QueryBuilders.functionScoreQuery(query, new ScriptScoreFunctionBuilder(script));
}
 
Example 5
Source File: ElasticsearchFieldValueScoringStrategy.java    From vertexium with Apache License 2.0 6 votes vote down vote up
@Override
public QueryBuilder updateElasticsearchQuery(
    Graph graph,
    Elasticsearch7SearchIndex searchIndex,
    QueryBuilder query,
    QueryParameters queryParameters
) {
    List<String> fieldNames = getFieldNames(graph, searchIndex, queryParameters, getField());
    if (fieldNames == null) {
        return query;
    }

    HashMap<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("fieldNames", fieldNames);
    Script script = new Script(ScriptType.INLINE, "painless", scriptSrc, scriptParams);
    return QueryBuilders.functionScoreQuery(query, new ScriptScoreFunctionBuilder(script));
}
 
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,
    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 7
Source File: CaseController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void update(String indexName) throws IOException {
    UpdateRequest request = new UpdateRequest(indexName, "1");
    Map<String, Object> parameters = singletonMap("title", "c++ programing.");
    Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.title = params.title", parameters);
    request.script(inline);

    UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
    if (updateResponse.getVersion() != 2) {
        String message = "elasticsearch update data fail.";
        logger.error(message);
        throw new RuntimeException(message);
    }
}
 
Example 8
Source File: ElasticsearchSearchQueryBase.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private Collection<? extends AggregationBuilder> getElasticsearchCalendarFieldAggregation(CalendarFieldAggregation agg) {
    List<AggregationBuilder> aggs = new ArrayList<>();
    PropertyDefinition propertyDefinition = getPropertyDefinition(agg.getPropertyName());
    if (propertyDefinition == null) {
        throw new VertexiumException("Could not find mapping for property: " + agg.getPropertyName());
    }
    Class propertyDataType = propertyDefinition.getDataType();
    for (String propertyName : getPropertyNames(agg.getPropertyName())) {
        String visibilityHash = getSearchIndex().getPropertyVisibilityHashFromPropertyName(propertyName);
        String aggName = createAggregationName(agg.getAggregationName(), visibilityHash);
        if (propertyDataType == Date.class) {
            HistogramAggregationBuilder histAgg = AggregationBuilders.histogram(aggName);
            histAgg.interval(1);
            if (agg.getMinDocumentCount() != null) {
                histAgg.minDocCount(agg.getMinDocumentCount());
            } else {
                histAgg.minDocCount(1L);
            }
            Script script = new Script(
                ScriptType.INLINE,
                "painless",
                getCalendarFieldAggregationScript(agg, propertyName),
                ImmutableMap.of(
                    "tzId", agg.getTimeZone().getID(),
                    "fieldName", propertyName,
                    "calendarField", agg.getCalendarField())
            );
            histAgg.script(script);

            for (AggregationBuilder subAgg : getElasticsearchAggregations(agg.getNestedAggregations())) {
                histAgg.subAggregation(subAgg);
            }

            aggs.add(histAgg);
        } else {
            throw new VertexiumException("Only dates are supported for hour of day aggregations");
        }
    }
    return aggs;
}
 
Example 9
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 10
Source File: ScriptFilter.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private void parseAndUpdateScriptType(String scriptType) {
    String scriptTypeUpper = scriptType.toUpperCase();
    switch(scriptTypeUpper){
        case "INLINE":
            this.scriptType = ScriptType.INLINE;
            break;
        case "INDEXED":
        case "STORED":
            this.scriptType = ScriptType.STORED;
            break;
    }
}
 
Example 11
Source File: ElasticsearchIndexer.java    From datashare with GNU Affero General Public License v3.0 5 votes vote down vote up
private Script createUntagScript(Tag[] tags) {
    return new Script(ScriptType.INLINE, "painless",
            "int updates = 0;" +
                    "for (int i = 0; i < params.tags.length; i++) {" +
                    "  if (ctx._source.tags.contains(params.tags[i])) {" +
                    "    ctx._source.tags.remove(ctx._source.tags.indexOf(params.tags[i]));" +
                    "    updates++;" +
                    "  }" +
                    "}" +
                    "if (updates == 0) ctx.op = 'noop';",
            new HashMap<String, Object>() {{put("tags", stream(tags).map(t -> t.label).collect(toList()));}});
}
 
Example 12
Source File: ProjectAnalyzer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static Script getScript(RexNode node,
    boolean painlessAllowed,
    boolean supportsV5Features,
    boolean scriptsEnabled,
    boolean isAggregationContext,
    boolean allowPushdownAnalyzedNormalizedFields,
    boolean variationDetected){
  ProjectAnalyzer analyzer = new ProjectAnalyzer(isAggregationContext, allowPushdownAnalyzedNormalizedFields);
  RenderMode mode = painlessAllowed && supportsV5Features ? RenderMode.PAINLESS : RenderMode.GROOVY;
  FunctionRenderer r = new FunctionRenderer(supportsV5Features, scriptsEnabled, mode, analyzer);
  analyzer.renderer = r;
  FunctionRender render = node.accept(analyzer);
  if(analyzer.isNotAllowed()){
    throw new RuntimeException(String.format("Failed to convert expression %s to script.", node));
  }

  String nullGuardedScript;
  if (isAggregationContext) {
    nullGuardedScript = render.getNullGuardedScript(variationDetected);
  } else {
    nullGuardedScript = render.getNullGuardedScript("false", variationDetected);
  }

  if (mode == RenderMode.PAINLESS) {
    // when returning a painless script, let's make sure we cast to a valid output type.
    return new Script(ScriptType.INLINE,  "painless", String.format("(def) (%s)", nullGuardedScript), ImmutableMap.of());
  } else {
    // keeping this so plan matching tests will pass
    return new Script(ScriptType.INLINE, "groovy", nullGuardedScript, ImmutableMap.of());
  }
}
 
Example 13
Source File: PredicateAnalyzer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static Script getScript(String script, StoragePluginId pluginId) {
  if (pluginId.getCapabilities().getCapability(ElasticsearchStoragePlugin.ENABLE_V5_FEATURES)) {
    // when returning a painless script, let's make sure we cast to a valid output type.
    return new Script(ScriptType.INLINE, "painless", String.format("(def) (%s)", script), ImmutableMap.of());
  } else {
    // keeping this so plan matching tests will pass
    return new Script(ScriptType.INLINE, "groovy", script, ImmutableMap.of());
  }
}
 
Example 14
Source File: PainlessScript.java    From vind with Apache License 2.0 5 votes vote down vote up
public Script build(Map<String, Object> parameters) {
    return new Script(
            ScriptType.INLINE,
            "painless",
            painlessScript.toString(),
            parameters);
}
 
Example 15
Source File: ElasticsearchJavaAPIScriptTest.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void scriptEqual() throws Exception {
    AbstractClient client = ElasticTestUtil.getDevClient();

    HashMap<String, Object> params = new HashMap<>();
    HashMap<String, Object> user0 = new HashMap<>();
    user0.put("id", LONG_ID);
    params.put("user0", user0);
    Script add = new Script(ScriptType.INLINE, "painless",
        "ctx._source.nested.add(params.user0);",
        params);

    params = new HashMap<>();
//    params.put("userId0", LONG_ID);
    params.put("userId0", EsTypeUtil.scriptConvert(LONG_ID));
    params.put("user0", user0);
    Script meta = new Script(ScriptType.INLINE, "painless",
        "if (ctx._source.nested == null) {ctx._source.nested = [];}if (ctx._source.nested.find(e -> e.id.equals(params.userId0)) == null) {\n" +
            "ctx._source.nested.add(params.user0);\n" +
            "}",
        params);

    BulkRequestBuilder bulkRequest = client.prepareBulk();
    bulkRequest.add(indexRequest(client, getSource()));
    bulkRequest.add(updateRequest(client, add));
    bulkRequest.add(updateRequest(client, meta));
    BulkResponse bulkItemResponses = bulkRequest.execute().actionGet();
    if (bulkItemResponses.hasFailures()) {
      for (BulkItemResponse itemResponse : bulkItemResponses.getItems()) {
        System.out.println(itemResponse.getFailure());
      }
//      Assert.fail();
    }
  }
 
Example 16
Source File: ElasticsearchJavaAPIScriptTest.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
   * https://discuss.elastic.co/t/java-api-plainless-script-indexof-give-wrong-answer/139016/7
   */
  public static void scriptIndexOf() throws Exception {
    AbstractClient client = ElasticTestUtil.getDevClient();

    HashMap<String, Object> params = new HashMap<>();
    params.put("users", LONG_ID);
    Script add = new Script(ScriptType.INLINE, "painless",
        "ctx._source.users.add(params.users);",
        params);
    Script meta = new Script(ScriptType.INLINE, "painless",
        "ctx._source.t1 = params.users; ctx._source.i11= ctx._source.users.indexOf(params.users); ctx._source.i21= ctx._source.users.lastIndexOf(params.users);",
        params);
    Script remove = new Script(ScriptType.INLINE, "painless",
        "ctx._source.users.remove(ctx._source.users.indexOf(params.users));",
        params);

    BulkRequestBuilder bulkRequest = client.prepareBulk();
    bulkRequest.add(indexRequest(client, getSource()));
    bulkRequest.add(updateRequest(client, add));
    bulkRequest.add(updateRequest(client, meta));
    bulkRequest.add(updateRequest(client, remove));
    bulkRequest.add(updateRequest(client, meta));
    BulkResponse bulkItemResponses = bulkRequest.execute().actionGet();
    if (bulkItemResponses.hasFailures()) {
      for (BulkItemResponse itemResponse : bulkItemResponses.getItems()) {
        System.out.println(itemResponse.getFailure());
      }
//      Assert.fail();
    }
  }
 
Example 17
Source File: DynamicRanker.java    From elasticsearch-dynarank with Apache License 2.0 5 votes vote down vote up
ScriptInfo(final String script, final String lang, final String scriptType, final Settings settings, final int reorderSize) {
    this.script = script;
    this.lang = lang;
    this.reorderSize = reorderSize;
    this.settings = new HashMap<>();
    for (final String name : settings.keySet()) {
        final List<String> list = settings.getAsList(name);
        this.settings.put(name, list.toArray(new String[list.size()]));
    }
    if ("STORED".equalsIgnoreCase(scriptType)) {
        this.scriptType = ScriptType.STORED;
    } else {
        this.scriptType = ScriptType.INLINE;
    }
}
 
Example 18
Source File: ESRequestMapper.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * https://www.elastic.co/guide/en/elasticsearch/reference/5.4/painless-api-reference.html
 */
private Script getScript(SyncData data, HashMap<String, Object> toSet) {
  HashMap<String, Object> params = new HashMap<>();
  StringBuilder code = new StringBuilder();
  ESScriptUpdate.makeScript(code, " = params.", ";", toSet, params);

  if (needScript(data)) {
    ESScriptUpdate esScriptUpdate = data.getEsScriptUpdate();
    esScriptUpdate.generateMergeScript(code, params);
  }

  return new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, code.toString(), params);
}
 
Example 19
Source File: NestedUpdateGroovyScritpBuilder.java    From search-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
/**
 * 删除标签脚本构建器
 *
 * @param nestedESObject 嵌套关系说明
 * @param idMap          待删除对象ID
 * @return delete tag groovy script
 */
private static Script deleteTag(NestedESObject nestedESObject, Map<Object, Object> idMap) {
    // 1 构建参数
    Map<String, Object> params = removerPrefix(idMap);
    StringBuilder sb = new StringBuilder();
    final String fieldName = nestedESObject.getFieldName();
    final NestedESObject nextNestedESObject = nestedESObject.getNextNestedESObject();

    if (nestedESObject.isList()) {
        if (!nestedESObject.hasNext()) {// 一级 集合嵌套添加
            sb.append("ctx._source.").append(fieldName);
            sb.append(".removeAll{it.id==id}");
        } else {// 二级 集合嵌套添加
            final String nextfieldName = nextNestedESObject.getFieldName();
            sb.append("ctx._source.").append(fieldName).append(".findAll{");
            final String[] idValues = nestedESObject.getIdValues();
            if (nestedESObject.hasRestriction()) {// 有筛选条件
                sb.append("if(");
                final int length = idValues.length;
                for (int i = 0; i < idValues.length; i++) {
                    params.put("id_" + i, idValues[i]);
                    sb.append("it.id==id_" + i);
                    if (i + 1 != length) {
                        sb.append("||");
                    }
                }
                sb.append(")");
                sb.append("{it.").append(nextfieldName).append(".removeAll{it.id==params.id}}}");
            } else {// 没有筛选条件
                sb.append("it.").append(nextfieldName).append(".removeAll {");
                sb.append("it.id").append("==params.id").append("}}");
            }
        }
    } else {// 一级为object 二级为集合
        //ctx._source.student.books.removeAll{it.size=id}
        sb.append("ctx._source.").append(fieldName).append(".").append(nextNestedESObject.getFieldName());
        sb.append(".removeAll{it.id==params.id}");
    }

    LOGGER.debug("nested data type delete painless script:[{}],params:{}", sb.toString(), params);
    return new Script(ScriptType.INLINE, "painless", sb.toString(), params);
}
 
Example 20
Source File: ScriptFilter.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
public ScriptFilter() {

        args = null;
        scriptType = ScriptType.INLINE;
    }