本文整理汇总了Java中org.elasticsearch.script.Script类的典型用法代码示例。如果您正苦于以下问题:Java Script类的具体用法?Java Script怎么用?Java Script使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Script类属于org.elasticsearch.script包,在下文中一共展示了Script类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testUnmapped
import org.elasticsearch.script.Script; //导入依赖的package包/类
public void testUnmapped() throws Exception {
SearchResponse response = client()
.prepareSearch("idx_unmapped")
.addAggregation(
histogram("histo")
.field(FIELD_1_NAME)
.interval(interval)
.subAggregation(sum("field2Sum").field(FIELD_2_NAME))
.subAggregation(sum("field3Sum").field(FIELD_3_NAME))
.subAggregation(sum("field4Sum").field(FIELD_4_NAME))
.subAggregation(
bucketScript("seriesArithmetic",
new Script(ScriptType.INLINE,
CustomScriptPlugin.NAME, "_value0 + _value1 + _value2", Collections.emptyMap()),
"field2Sum", "field3Sum", "field4Sum")))
.execute().actionGet();
assertSearchResponse(response);
Histogram deriv = response.getAggregations().get("histo");
assertThat(deriv, notNullValue());
assertThat(deriv.getName(), equalTo("histo"));
assertThat(deriv.getBuckets().size(), equalTo(0));
}
示例2: removeFieldsFromDocument
import org.elasticsearch.script.Script; //导入依赖的package包/类
/**
* Helper method to remove fields from source. This method will generate a ES update request. Retries on conflict.
*
* @param graph Graph object configured with the index names
* @param element Element that can be mapped to an ES document
* @param fields fields to remove
*/
private void removeFieldsFromDocument(Graph graph, Element element, Collection<String> fields) {
if (fields == null || fields.isEmpty()) {
return;
}
List<String> fieldNames = fields.stream().map(field -> field.replace(".", FIELDNAME_DOT_REPLACEMENT)).collect(Collectors.toList());
if (fieldNames.isEmpty()) {
return;
}
UpdateRequestBuilder updateRequestBuilder = getClient().prepareUpdate()
.setIndex(getIndexName(element))
.setId(element.getId())
.setType(ELEMENT_TYPE)
.setScript(new Script(
ScriptType.INLINE,
"painless",
"for (def fieldName : params.fieldNames) { ctx._source.remove(fieldName); }",
ImmutableMap.of("fieldNames", fieldNames)
))
.setRetryOnConflict(MAX_RETRIES);
addActionRequestBuilderForFlush(element.getId(), updateRequestBuilder);
if (getConfig().isAutoFlush()) {
flush(graph);
}
}
示例3: getElasticsearchCalendarFieldAggregation
import org.elasticsearch.script.Script; //导入依赖的package包/类
private Collection<? extends AggregationBuilder> getElasticsearchCalendarFieldAggregation(CalendarFieldAggregation agg) {
List<AggregationBuilder> aggs = new ArrayList<>();
PropertyDefinition propertyDefinition = getPropertyDefinition(agg.getPropertyName());
if (propertyDefinition == null) {
throw new MemgraphException("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 MemgraphException("Only dates are supported for hour of day aggregations");
}
}
return aggs;
}
示例4: testInvalidUpdateScript
import org.elasticsearch.script.Script; //导入依赖的package包/类
public void testInvalidUpdateScript() throws Exception {
try {
createIndex("test_index");
ensureGreen("test_index");
indexRandom(true, client().prepareIndex("test_index", "doc", "1").setSource("text_field", "text"));
UpdateRequestBuilder urb = client().prepareUpdate().setIndex("test_index");
urb.setType("doc");
urb.setId("1");
urb.setScript(new Script(ScriptType.INLINE, ExpressionScriptEngineService.NAME, "0", Collections.emptyMap()));
urb.get();
fail("Expression scripts should not be allowed to run as update scripts.");
} catch (Exception e) {
String message = e.getMessage();
assertThat(message + " should have contained failed to execute", message.contains("failed to execute"), equalTo(true));
message = e.getCause().getMessage();
assertThat(message + " should have contained not supported", message.contains("not supported"), equalTo(true));
}
}
示例5: createTestAggregatorBuilder
import org.elasticsearch.script.Script; //导入依赖的package包/类
@Override
protected final AF createTestAggregatorBuilder() {
AF factory = doCreateTestAggregatorFactory();
String field = randomNumericField();
int randomFieldBranch = randomInt(3);
switch (randomFieldBranch) {
case 0:
factory.field(field);
break;
case 1:
factory.field(field);
factory.script(new Script("_value + 1"));
break;
case 2:
factory.script(new Script("doc[" + field + "] + 1"));
break;
}
if (randomBoolean()) {
factory.missing("MISSING");
}
return factory;
}
示例6: internalXContent
import org.elasticsearch.script.Script; //导入依赖的package包/类
@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();
}
示例7: testInlineScriptNoBucketsLeft
import org.elasticsearch.script.Script; //导入依赖的package包/类
public void testInlineScriptNoBucketsLeft() {
Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME,
"Double.isNaN(_value0) ? false : (_value0 > 10000)", Collections.emptyMap());
SearchResponse response = client()
.prepareSearch("idx")
.addAggregation(
histogram("histo")
.field(FIELD_1_NAME)
.interval(interval)
.subAggregation(sum("field2Sum").field(FIELD_2_NAME))
.subAggregation(sum("field3Sum").field(FIELD_3_NAME))
.subAggregation(bucketSelector("bucketSelector", script, "field2Sum", "field3Sum")))
.execute().actionGet();
assertSearchResponse(response);
Histogram histo = response.getAggregations().get("histo");
assertThat(histo, notNullValue());
assertThat(histo.getName(), equalTo("histo"));
List<? extends Bucket> buckets = histo.getBuckets();
assertThat(buckets.size(), equalTo(0));
}
示例8: testSimpleBulk4
import org.elasticsearch.script.Script; //导入依赖的package包/类
public void testSimpleBulk4() throws Exception {
String bulkAction = copyToStringFromClasspath("/org/elasticsearch/action/bulk/simple-bulk4.json");
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, null, XContentType.JSON);
assertThat(bulkRequest.numberOfActions(), equalTo(4));
assertThat(((UpdateRequest) bulkRequest.requests().get(0)).id(), equalTo("1"));
assertThat(((UpdateRequest) bulkRequest.requests().get(0)).retryOnConflict(), equalTo(2));
assertThat(((UpdateRequest) bulkRequest.requests().get(0)).doc().source().utf8ToString(), equalTo("{\"field\":\"value\"}"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).id(), equalTo("0"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).type(), equalTo("type1"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).index(), equalTo("index1"));
Script script = ((UpdateRequest) bulkRequest.requests().get(1)).script();
assertThat(script, notNullValue());
assertThat(script.getIdOrCode(), equalTo("counter += param1"));
assertThat(script.getLang(), equalTo("javascript"));
Map<String, Object> scriptParams = script.getParams();
assertThat(scriptParams, notNullValue());
assertThat(scriptParams.size(), equalTo(1));
assertThat(((Integer) scriptParams.get("param1")), equalTo(1));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).upsertRequest().source().utf8ToString(), equalTo("{\"counter\":1}"));
}
示例9: createInternal
import org.elasticsearch.script.Script; //导入依赖的package包/类
@Override
public Aggregator createInternal(Aggregator parent, boolean collectsFromSingleBucket, List<PipelineAggregator> pipelineAggregators,
Map<String, Object> metaData) throws IOException {
if (collectsFromSingleBucket == false) {
return asMultiBucketAggregator(this, context, parent);
}
Map<String, Object> params = this.params;
if (params != null) {
params = deepCopyParams(params, context);
} else {
params = new HashMap<>();
params.put("_agg", new HashMap<String, Object>());
}
final ExecutableScript initScript = this.initScript.apply(params);
final SearchScript mapScript = this.mapScript.apply(params);
final ExecutableScript combineScript = this.combineScript.apply(params);
final Script reduceScript = deepCopyScript(this.reduceScript, context);
if (initScript != null) {
initScript.run();
}
return new ScriptedMetricAggregator(name, mapScript,
combineScript, reduceScript, params, context, parent,
pipelineAggregators, metaData);
}
示例10: parse
import org.elasticsearch.script.Script; //导入依赖的package包/类
public static SignificanceHeuristic parse(QueryParseContext context)
throws IOException, QueryShardException {
XContentParser parser = context.parser();
String heuristicName = parser.currentName();
Script script = null;
XContentParser.Token token;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token.equals(XContentParser.Token.FIELD_NAME)) {
currentFieldName = parser.currentName();
} else {
if (Script.SCRIPT_PARSE_FIELD.match(currentFieldName)) {
script = Script.parse(parser);
} else {
throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown object [{}]", heuristicName, currentFieldName);
}
}
}
if (script == null) {
throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. no script found in script_heuristic", heuristicName);
}
return new ScriptHeuristic(script);
}
示例11: testScriptScoresNested
import org.elasticsearch.script.Script; //导入依赖的package包/类
public void testScriptScoresNested() throws IOException {
createIndex(INDEX);
index(INDEX, TYPE, "1", jsonBuilder().startObject().field("dummy_field", 1).endObject());
refresh();
Script scriptOne = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "1", Collections.emptyMap());
Script scriptTwo = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "get score value", Collections.emptyMap());
SearchResponse response = client().search(
searchRequest().source(
searchSource().query(
functionScoreQuery(
functionScoreQuery(
functionScoreQuery(scriptFunction(scriptOne)),
scriptFunction(scriptTwo)),
scriptFunction(scriptTwo)
)
)
)
).actionGet();
assertSearchResponse(response);
assertThat(response.getHits().getAt(0).getScore(), equalTo(1.0f));
}
示例12: testDontCacheScripts
import org.elasticsearch.script.Script; //导入依赖的package包/类
/**
* Make sure that a request using a script does not get cached and a request
* not using a script does get cached.
*/
public void testDontCacheScripts() throws Exception {
assertAcked(prepareCreate("cache_test_idx").addMapping("type", "d", "type=long")
.setSettings(Settings.builder().put("requests.cache.enable", true).put("number_of_shards", 1).put("number_of_replicas", 1))
.get());
indexRandom(true, client().prepareIndex("cache_test_idx", "type", "1").setSource("s", 1),
client().prepareIndex("cache_test_idx", "type", "2").setSource("s", 2));
// Make sure we are starting with a clear cache
assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
.getHitCount(), equalTo(0L));
assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
.getMissCount(), equalTo(0L));
// Test that a request using a script does not get cached
SearchResponse r = client().prepareSearch("cache_test_idx").setSize(0)
.addAggregation(count("foo").field("d").script(
new Script(ScriptType.INLINE, FieldValueScriptEngine.NAME, "value", Collections.emptyMap())))
.get();
assertSearchResponse(r);
assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
.getHitCount(), equalTo(0L));
assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
.getMissCount(), equalTo(0L));
// To make sure that the cache is working test that a request not using
// a script is cached
r = client().prepareSearch("cache_test_idx").setSize(0).addAggregation(count("foo").field("d")).get();
assertSearchResponse(r);
assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
.getHitCount(), equalTo(0L));
assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
.getMissCount(), equalTo(1L));
}
示例13: testMultiValuedNumericScript
import org.elasticsearch.script.Script; //导入依赖的package包/类
public void testMultiValuedNumericScript() throws Exception {
Script script =
new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc[' + multiNumericField(false) + '].values", Collections.emptyMap());
SearchResponse response = client().prepareSearch("idx").setTypes("type")
.addAggregation(cardinality("cardinality").precisionThreshold(precisionThreshold).script(script))
.execute().actionGet();
assertSearchResponse(response);
Cardinality count = response.getAggregations().get("cardinality");
assertThat(count, notNullValue());
assertThat(count.getName(), equalTo("cardinality"));
assertCount(count, numDocs * 2);
}
示例14: testNativeExplainScript
import org.elasticsearch.script.Script; //导入依赖的package包/类
public void testNativeExplainScript() throws InterruptedException, IOException, ExecutionException {
List<IndexRequestBuilder> indexRequests = new ArrayList<>();
for (int i = 0; i < 20; i++) {
indexRequests.add(client().prepareIndex("test", "type").setId(Integer.toString(i)).setSource(
jsonBuilder().startObject().field("number_field", i).field("text", "text").endObject()));
}
indexRandom(true, true, indexRequests);
client().admin().indices().prepareRefresh().execute().actionGet();
ensureYellow();
SearchResponse response = client().search(searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source(
searchSource().explain(true).query(
functionScoreQuery(termQuery("text", "text"),
scriptFunction(
new Script(ScriptType.INLINE, "native", "native_explainable_script", Collections.emptyMap())))
.boostMode(CombineFunction.REPLACE)))).actionGet();
ElasticsearchAssertions.assertNoFailures(response);
SearchHits hits = response.getHits();
assertThat(hits.getTotalHits(), equalTo(20L));
int idCounter = 19;
for (SearchHit hit : hits.getHits()) {
assertThat(hit.getId(), equalTo(Integer.toString(idCounter)));
assertThat(hit.getExplanation().toString(),
containsString(Double.toString(idCounter) + " = This script returned " + Double.toString(idCounter)));
assertThat(hit.getExplanation().toString(), containsString("freq=1.0 = termFreq=1.0"));
assertThat(hit.getExplanation().getDetails().length, equalTo(2));
idCounter--;
}
}
示例15: testStringSpecialValueVariable
import org.elasticsearch.script.Script; //导入依赖的package包/类
public void testStringSpecialValueVariable() throws Exception {
// i.e. expression script for term aggregations, which is not allowed
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("doc", "text", "type=keyword").get());
ensureGreen("test");
indexRandom(true,
client().prepareIndex("test", "doc", "1").setSource("text", "hello"),
client().prepareIndex("test", "doc", "2").setSource("text", "goodbye"),
client().prepareIndex("test", "doc", "3").setSource("text", "hello"));
SearchRequestBuilder req = client().prepareSearch().setIndices("test");
req.setQuery(QueryBuilders.matchAllQuery())
.addAggregation(
AggregationBuilders.terms("term_agg").field("text")
.script(
new Script(ScriptType.INLINE, ExpressionScriptEngineService.NAME, "_value", Collections.emptyMap())));
String message;
try {
// shards that don't have docs with the "text" field will not fail,
// so we may or may not get a total failure
SearchResponse rsp = req.get();
assertThat(rsp.getShardFailures().length, greaterThan(0)); // at least the shards containing the docs should have failed
message = rsp.getShardFailures()[0].reason();
} catch (SearchPhaseExecutionException e) {
message = e.toString();
}
assertThat(message + "should have contained ScriptException",
message.contains("ScriptException"), equalTo(true));
assertThat(message + "should have contained text variable error",
message.contains("text variable"), equalTo(true));
}