Java Code Examples for org.elasticsearch.script.Script

The following examples show how to use org.elasticsearch.script.Script. These examples are extracted from open source projects. 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 Project: elasticsearch-sql   Source File: UpdateQueryParser.java    License: MIT License 6 votes vote down vote up
private void parseUpdateByQuery(ElasticDslContext dslContext) {
    dslContext.getParseResult().setSqlOperation(SqlOperation.UPDATE_BY_QUERY);
    ElasticsearchParser.UpdateOperationContext updateOperationContext = dslContext.getSqlContext().updateOperation();
    String indexName = updateOperationContext.tableRef().indexName.getText();
    UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest(indexName);
    int size = updateOperationContext.ID().size();
    StringBuilder builder = new StringBuilder();
    Map<String, Object> params = new HashMap<>(0);
    for (int i = 0; i < size; i++) {
        builder.append(UPDATE_PREFIX).append(updateOperationContext.ID(i).getText()).append('=');
        if (updateOperationContext.identity(i).identityList() != null) {
            builder.append("params.").append(PARAM_PREFIX).append(params.size());
            params.put(PARAM_PREFIX + params.size(), parseIdentityList(updateOperationContext.identity(i).identityList().identity()));
        } else if (updateOperationContext.identity(i).STRING() != null) {
            builder.append('\'').append(StringManager.removeStringSymbol(updateOperationContext.identity(i).STRING().getText())).append('\'');
        } else {
            builder.append(updateOperationContext.identity(i).number.getText());
        }
        builder.append(';');
    }
    updateByQueryRequest.setScript(new Script(ScriptType.INLINE, "painless", builder.toString(), params));
    if (updateOperationContext.routingClause() != null) {
        updateByQueryRequest.setRouting(StringManager.removeStringSymbol(updateOperationContext.routingClause().STRING(0).getText()));
    }
    if (updateOperationContext.whereClause() != null) {
        BoolExpressionParser boolExpressionParser = new BoolExpressionParser();
        updateByQueryRequest.setQuery(boolExpressionParser.parseBoolQueryExpr(updateOperationContext.whereClause().expression()));
    } else {
        updateByQueryRequest.setQuery(QueryBuilders.matchAllQuery());
    }
    if (updateOperationContext.batchClause() != null) {
        updateByQueryRequest.setBatchSize(Integer.parseInt(updateOperationContext.batchClause().size.getText()));
    }
    if (updateOperationContext.limitClause() != null) {
        updateByQueryRequest.setMaxDocs(Integer.parseInt(updateOperationContext.limitClause().size.getText()));
    }
    dslContext.getParseResult().setUpdateByQueryRequest(updateByQueryRequest);
}
 
Example 2
@Override
protected void unlock(TransactionDefinition definition) {
    // 尝试解锁
    String key = definition.getName();
    Long value = definition.getMost().toEpochMilli();
    Map<String, Object> document = new HashMap<>();
    document.put(NAME, key);
    document.put(MOST, value);
    document.put(NOW, Instant.now().toEpochMilli());
    UpdateRequest request = new UpdateRequest().index(index).type(type)

            .id(key)

            .script(new Script(ScriptType.INLINE, SCRIPT, UNLOCK_SCRIPT, document));
    try {
        UpdateResponse response = elastic.update(request, RequestOptions.DEFAULT);
        if (response.getResult() == DocWriteResponse.Result.NOOP) {
            throw new TransactionUnlockException();
        }
    } catch (Exception exception) {
        throw new TransactionUnlockException(exception);
    }
}
 
Example 3
@Override
protected final XContentBuilder internalXContent(XContentBuilder builder, Params builderParams) throws IOException {
    builder.startObject();
    if (field != null) {
        builder.field("field", field);
    }

    if (script == null) {
        if (scriptString != null) {
            builder.field("script", new Script(scriptString, ScriptType.INLINE, lang, params));
        }
    } else {
        builder.field("script", script);
    }
    if (missing != null) {
        builder.field("missing", missing);
    }

    doInternalXContent(builder, builderParams);
    return builder.endObject();
}
 
Example 4
Source Project: Elasticsearch   Source File: ScriptedMetricAggregator.java    License: Apache License 2.0 6 votes vote down vote up
protected ScriptedMetricAggregator(String name, Script initScript, Script mapScript, Script combineScript, Script reduceScript,
        Map<String, Object> params, AggregationContext context, Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData)
        throws IOException {
    super(name, context, parent, pipelineAggregators, metaData);
    this.params = params;
    ScriptService scriptService = context.searchContext().scriptService();
    if (initScript != null) {
        scriptService.executable(initScript, ScriptContext.Standard.AGGS, context.searchContext(), Collections.<String, String>emptyMap()).run();
    }
    this.mapScript = scriptService.search(context.searchContext().lookup(), mapScript, ScriptContext.Standard.AGGS, Collections.<String, String>emptyMap());
    if (combineScript != null) {
        this.combineScript = scriptService.executable(combineScript, ScriptContext.Standard.AGGS, context.searchContext(), Collections.<String, String>emptyMap());
    } else {
        this.combineScript = null;
    }
    this.reduceScript = reduceScript;
}
 
Example 5
Source Project: Elasticsearch   Source File: ScriptHeuristic.java    License: Apache License 2.0 6 votes vote down vote up
public ScriptHeuristic(ExecutableScript searchScript, Script script) {
    subsetSizeHolder = new LongAccessor();
    supersetSizeHolder = new LongAccessor();
    subsetDfHolder = new LongAccessor();
    supersetDfHolder = new LongAccessor();
    this.searchScript = searchScript;
    if (searchScript != null) {
        searchScript.setNextVar("_subset_freq", subsetDfHolder);
        searchScript.setNextVar("_subset_size", subsetSizeHolder);
        searchScript.setNextVar("_superset_freq", supersetDfHolder);
        searchScript.setNextVar("_superset_size", supersetSizeHolder);
    }
    this.script = script;


}
 
Example 6
@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 7
Source Project: Elasticsearch   Source File: ScriptSortBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params builderParams) throws IOException {
    builder.startObject("_script");
    if (script == null) {

        builder.field("script", new Script(scriptString, ScriptType.INLINE, lang, params));
    } else {
        builder.field("script", script);
    }
    builder.field("type", type);
    if (order == SortOrder.DESC) {
        builder.field("order", "desc");
    }
    if (sortMode != null) {
        builder.field("mode", sortMode);
    }
    if (nestedPath != null) {
        builder.field("nested_path", nestedPath);
    }
    if (nestedFilter != null) {
        builder.field("nested_filter", nestedFilter, builderParams);
    }
    builder.endObject();
    return builder;
}
 
Example 8
@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 9
@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 10
Source Project: dremio-oss   Source File: PredicateAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
private static QueryBuilder genScriptFilter(RexNode expression, StoragePluginId pluginId, boolean variationDetected, Throwable cause)
    throws ExpressionNotAnalyzableException {
  try {
    final boolean supportsV5Features = pluginId.getCapabilities().getCapability(ElasticsearchStoragePlugin.ENABLE_V5_FEATURES);
    final ElasticsearchConf config = ElasticsearchConf.createElasticsearchConf(pluginId.getConnectionConf());
    final Script script = ProjectAnalyzer.getScript(
        expression,
        config.isUsePainless(),
        supportsV5Features,
        config.isScriptsEnabled(),
        false, /* _source is not available in filter context */
        config.isAllowPushdownOnNormalizedOrAnalyzedFields(),
        variationDetected);
    QueryBuilder builder = scriptQuery(script);
    return builder;
  } catch (Throwable t) {
    cause.addSuppressed(t);
    throw new ExpressionNotAnalyzableException(format(
        "Failed to fully convert predicate: [%s] into an elasticsearch filter", expression), cause);
  }
}
 
Example 11
@SuppressWarnings("unchecked")
public ScriptFeature(String name, Script script, Collection<String> queryParams) {
    this.name = Objects.requireNonNull(name);
    this.script = Objects.requireNonNull(script);
    this.queryParams = queryParams;
    Map<String, Object> ltrScriptParams = new HashMap<>();
    Map<String, String> ltrExtraScriptParams = new HashMap<>();
    for (Map.Entry<String, Object> entry : script.getParams().entrySet()) {
        if (!entry.getKey().equals(EXTRA_SCRIPT_PARAMS)) {
            ltrScriptParams.put(String.valueOf(entry.getKey()), entry.getValue());
        } else {
            ltrExtraScriptParams = (Map<String, String>) entry.getValue();
        }
    }
    this.baseScriptParams = ltrScriptParams;
    this.extraScriptParams = ltrExtraScriptParams;
}
 
Example 12
@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 13
Source Project: elasticsearch-sql   Source File: DefaultQueryAction.java    License: 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 14
Source Project: ShedLock   Source File: ElasticsearchLockProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doUnlock() {
    // Set lockUtil to now or lockAtLeastUntil whichever is later
    try {
        UpdateRequest ur = new UpdateRequest()
            .index(index)
            .type(type)
            .id(lockConfiguration.getName())
            .script(new Script(ScriptType.INLINE,
                "painless",
                "ctx._source.lockUntil = params.unlockTime",
                Collections.singletonMap("unlockTime", lockConfiguration.getUnlockTime().toEpochMilli())));
        highLevelClient.update(ur, RequestOptions.DEFAULT);
    } catch (IOException | ElasticsearchException e) {
        throw new LockException("Unexpected exception occurred", e);
    }
}
 
Example 15
Source Project: vertexium   Source File: ElasticsearchSearchQueryBase.java    License: 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 16
public Script build(NestedESObject nestedESObject, OperateTypeEnum operateType, Map<Object, Object> dataMap) {
    switch (operateType) {
        case ADD:
            return addTag(nestedESObject, dataMap);
        case UPDATE:
            return updateTag(nestedESObject, dataMap);
        case DELETE:
            return deleteTag(nestedESObject, dataMap);
        default:
            return null;
    }
}
 
Example 17
Source Project: elasticsearch-sql   Source File: ReindexQueryParser.java    License: MIT License 5 votes vote down vote up
private void buildScript(ElasticsearchParser.ReindexOperationContext reindexOperationContext, ReindexRequest reindexRequest) {
    StringBuilder script = new StringBuilder();
    for (ElasticsearchParser.NameOperandContext nameOperandContext : reindexOperationContext.fieldList().nameOperand()) {
        if (nameOperandContext.exclude != null) {
            script.append("ctx._source.remove('").append(nameOperandContext.fieldName.getText()).append("')';");
        }
    }
    if (StringUtils.isNotBlank(script.toString())) {
        reindexRequest.setScript(new Script(ScriptType.INLINE, "painless", script.toString(), Collections.emptyMap()));
    }
}
 
Example 18
Source Project: Mahuta   Source File: ElasticSearchService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void updateField(String indexName, String indexDocId, String key, Object value) {
    log.debug("Update field on document in ElasticSearch [indexName: {}, indexDocId: {}, key: {}, value: {}]", indexName, indexDocId, key, value);

    // Validation
    ValidatorUtils.rejectIfEmpty("indexName", indexName);
    ValidatorUtils.rejectIfEmpty("indexDocId", indexDocId);
    ValidatorUtils.rejectIfEmpty("key", key);

    // Format index
    indexName = indexName.toLowerCase();
    
    try {
        Map<String, Object> params = new HashMap<>();
        params.put("value", transformValue(value));
        
        client.prepareUpdate(indexName, DEFAULT_TYPE, indexDocId)
            .setRetryOnConflict(RETRY_ON_CONFLICT)
            .setScript(new Script(
                    ScriptType.INLINE,
                    "painless",
                    "ctx._source."+key+" = params.value",
                    params
            )).execute().actionGet();

        log.debug("Field updated on document in ElasticSearch [indexName: {}, indexDocId: {}, key: {}, value: {}]", indexName, indexDocId, key, value);

        this.refreshIndex(indexName);

    } catch (Exception ex) {
        log.error("Error while updating field [indexName: {}, indexDocId: {}, key: {}, value: {}]", indexName, indexDocId, key, value, ex);
        throw new TechnicalException("Error while updating key " + key + " of doc indexDocId: " + indexDocId, ex);
    }
}
 
Example 19
@Override
protected void lock(TransactionDefinition definition) {
    // 尝试加锁
    String key = definition.getName();
    Long value = definition.getMost().toEpochMilli();
    Map<String, Object> document = new HashMap<>();
    document.put(NAME, key);
    document.put(MOST, value);
    document.put(NOW, Instant.now().toEpochMilli());
    UpdateRequest request = new UpdateRequest().index(index).type(type)

            .id(key)

            .script(new Script(ScriptType.INLINE, SCRIPT, LOCK_SCRIPT, document))

            .upsert(document)

            .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
    try {
        UpdateResponse response = elastic.update(request, RequestOptions.DEFAULT);
        if (response.getResult() == DocWriteResponse.Result.NOOP) {
            throw new TransactionLockException();
        }
    } catch (Exception exception) {
        throw new TransactionLockException(exception);
    }

}
 
Example 20
/**
 * 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 21
Source Project: skywalking   Source File: RestHighLevelClientCase.java    License: Apache License 2.0 5 votes vote down vote up
private void update(RestHighLevelClient client, String indexName) throws IOException {
    UpdateRequest request = new UpdateRequest(indexName, "_doc", "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 22
/**
   * 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 23
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 24
Source Project: vind   Source File: PainlessScript.java    License: 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 25
Source Project: jframe   Source File: TestTransportClient.java    License: Apache License 2.0 5 votes vote down vote up
public void testUpdate() throws Exception {
    UpdateRequest updateRequest = new UpdateRequest();
    updateRequest.index("index");
    updateRequest.type("type");
    updateRequest.id("1");
    updateRequest.doc(XContentFactory.jsonBuilder().startObject().field("gender", "male").endObject());
    UpdateResponse response = client.update(updateRequest).get();
    System.out.println(response.toString());

    client.prepareUpdate("ttl", "doc", "1").setScript(new Script("ctx._source.gender = \"male\"", ScriptService.ScriptType.INLINE, null, null))
            .get();

    client.prepareUpdate("ttl", "doc", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("gender", "male").endObject()).get();
}
 
Example 26
Source Project: Elasticsearch   Source File: ScriptedMetricAggregator.java    License: Apache License 2.0 5 votes vote down vote up
private static Script deepCopyScript(Script script, SearchContext context) {
    if (script != null) {
        Map<String, Object> params = script.getParams();
        if (params != null) {
            params = deepCopyParams(params, context);
        }
        return new Script(script.getScript(), script.getType(), script.getLang(), params);
    } else {
        return null;
    }
}
 
Example 27
Source Project: vertexium   Source File: BulkUpdateItem.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void addToBulkRequest(Client client, BulkRequestBuilder bulkRequestBuilder) {
    UpdateRequestBuilder updateRequestBuilder = client
        .prepareUpdate(getIndexName(), getType(), getDocumentId());
    if (!updateOnly) {
        updateRequestBuilder = updateRequestBuilder
            .setScriptedUpsert(true)
            .setUpsert(source);
    }
    UpdateRequest updateRequest = updateRequestBuilder
        .setScript(new Script(
            ScriptType.STORED,
            "painless",
            "updateFieldsOnDocumentScript",
            ImmutableMap.of(
                "fieldsToSet", fieldsToSet.entrySet().stream()
                    .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> new ArrayList<>(entry.getValue())
                    )),
                "fieldsToRemove", new ArrayList<>(fieldsToRemove),
                "fieldsToRename", fieldsToRename,
                "additionalVisibilities", new ArrayList<>(additionalVisibilities),
                "additionalVisibilitiesToDelete", new ArrayList<>(additionalVisibilitiesToDelete)
            )
        ))
        .setRetryOnConflict(Elasticsearch5SearchIndex.MAX_RETRIES)
        .request();
    bulkRequestBuilder.add(updateRequest);
}
 
Example 28
Source Project: Elasticsearch   Source File: InternalScriptedMetric.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doReadFrom(StreamInput in) throws IOException {
    if (in.readBoolean()) {
        reduceScript = Script.readScript(in);
    }
    aggregation = in.readGenericValue();
}
 
Example 29
Source Project: vertexium   Source File: BulkUpdateItem.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void addToBulkRequest(Client client, BulkRequestBuilder bulkRequestBuilder) {
    UpdateRequestBuilder updateRequestBuilder = client
        .prepareUpdate(getIndexName(), getType(), getDocumentId());
    if (!updateOnly) {
        updateRequestBuilder = updateRequestBuilder
            .setScriptedUpsert(true)
            .setUpsert((Map<String, Object>) (Map) source);
    }
    UpdateRequest updateRequest = updateRequestBuilder
        .setScript(new Script(
            ScriptType.STORED,
            null,
            "updateFieldsOnDocumentScript",
            ImmutableMap.of(
                "fieldsToSet", fieldsToSet.entrySet().stream()
                    .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> new ArrayList<>(entry.getValue())
                    )),
                "fieldsToRemove", new ArrayList<>(fieldsToRemove),
                "fieldsToRename", fieldsToRename,
                "additionalVisibilities", new ArrayList<>(additionalVisibilities),
                "additionalVisibilitiesToDelete", new ArrayList<>(additionalVisibilitiesToDelete)
            )
        ))
        .setRetryOnConflict(Elasticsearch7SearchIndex.MAX_RETRIES)
        .request();
    bulkRequestBuilder.add(updateRequest);
}
 
Example 30
@SuppressWarnings("unchecked")
@Override
protected void doReadFrom(StreamInput in) throws IOException {
    script = Script.readScript(in);
    gapPolicy = GapPolicy.readFrom(in);
    bucketsPathsMap = (Map<String, String>) in.readGenericValue();
}