本文整理汇总了Java中org.elasticsearch.index.query.QueryShardContext类的典型用法代码示例。如果您正苦于以下问题:Java QueryShardContext类的具体用法?Java QueryShardContext怎么用?Java QueryShardContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
QueryShardContext类属于org.elasticsearch.index.query包,在下文中一共展示了QueryShardContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testKeyword
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
public void testKeyword() throws Exception {
IndexService indexService = createIndex("index", Settings.EMPTY, "type",
"bytes", "type=keyword");
client().prepareIndex("index", "type", "1")
.setSource("bytes", "abc")
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.get();
try (Searcher searcher = indexService.getShard(0).acquireSearcher("test")) {
QueryShardContext context = indexService.newQueryShardContext(0, searcher.reader(), () -> 42L);
ValuesSourceConfig<ValuesSource.Bytes> config = ValuesSourceConfig.resolve(
context, null, "bytes", null, null, null, null);
ValuesSource.Bytes valuesSource = config.toValuesSource(context);
LeafReaderContext ctx = searcher.reader().leaves().get(0);
SortedBinaryDocValues values = valuesSource.bytesValues(ctx);
values.setDocument(0);
assertEquals(1, values.count());
assertEquals(new BytesRef("abc"), values.valueAt(0));
}
}
示例2: toQuery
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
static Query toQuery(QueryShardContext context, boolean mapUnmappedFieldsAsString, QueryBuilder queryBuilder) throws IOException {
// This means that fields in the query need to exist in the mapping prior to registering this query
// The reason that this is required, is that if a field doesn't exist then the query assumes defaults, which may be undesired.
//
// Even worse when fields mentioned in percolator queries do go added to map after the queries have been registered
// then the percolator queries don't work as expected any more.
//
// Query parsing can't introduce new fields in mappings (which happens when registering a percolator query),
// because field type can't be inferred from queries (like document do) so the best option here is to disallow
// the usage of unmapped fields in percolator queries to avoid unexpected behaviour
//
// if index.percolator.map_unmapped_fields_as_string is set to true, query can contain unmapped fields which will be mapped
// as an analyzed string.
context.setAllowUnmappedFields(false);
context.setMapUnmappedFieldAsString(mapUnmappedFieldsAsString);
return queryBuilder.toQuery(context);
}
示例3: testBlendNoTermQuery
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
public void testBlendNoTermQuery() {
FakeFieldType ft1 = new FakeFieldType();
ft1.setName("foo");
FakeFieldType ft2 = new FakeFieldType() {
@Override
public Query termQuery(Object value, QueryShardContext context) {
return new MatchAllDocsQuery();
}
};
ft2.setName("bar");
Term[] terms = new Term[] { new Term("foo", "baz") };
float[] boosts = new float[] {2};
Query expectedClause1 = BlendedTermQuery.booleanBlendedQuery(terms, boosts, false);
Query expectedClause2 = new BoostQuery(new MatchAllDocsQuery(), 3);
Query expected = new BooleanQuery.Builder().setDisableCoord(true)
.add(expectedClause1, Occur.SHOULD)
.add(expectedClause2, Occur.SHOULD)
.build();
Query actual = MultiMatchQuery.blendTerm(
indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }),
new BytesRef("baz"), null, 1f, new FieldAndFieldType(ft1, 2), new FieldAndFieldType(ft2, 3));
assertEquals(expected, actual);
}
示例4: testLong
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
public void testLong() throws Exception {
IndexService indexService = createIndex("index", Settings.EMPTY, "type",
"long", "type=long");
client().prepareIndex("index", "type", "1")
.setSource("long", 42)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.get();
try (Searcher searcher = indexService.getShard(0).acquireSearcher("test")) {
QueryShardContext context = indexService.newQueryShardContext(0, searcher.reader(), () -> 42L);
ValuesSourceConfig<ValuesSource.Numeric> config = ValuesSourceConfig.resolve(
context, null, "long", null, null, null, null);
ValuesSource.Numeric valuesSource = config.toValuesSource(context);
LeafReaderContext ctx = searcher.reader().leaves().get(0);
SortedNumericDocValues values = valuesSource.longValues(ctx);
values.setDocument(0);
assertEquals(1, values.count());
assertEquals(42, values.valueAt(0));
}
}
示例5: testRangeQuery
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
public void testRangeQuery() throws Exception {
Settings indexSettings = Settings.builder()
.put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings(randomAsciiOfLengthBetween(1, 10), indexSettings);
QueryShardContext context = new QueryShardContext(0, idxSettings, null, null, null, null, null, xContentRegistry(),
null, null, () -> nowInMillis);
RangeFieldMapper.RangeFieldType ft = new RangeFieldMapper.RangeFieldType(type);
ft.setName(FIELDNAME);
ft.setIndexOptions(IndexOptions.DOCS);
ShapeRelation relation = RandomPicks.randomFrom(random(), ShapeRelation.values());
boolean includeLower = random().nextBoolean();
boolean includeUpper = random().nextBoolean();
Object from = nextFrom();
Object to = nextTo(from);
assertEquals(getExpectedRangeQuery(relation, from, to, includeLower, includeUpper),
ft.rangeQuery(from, to, includeLower, includeUpper, relation, context));
}
示例6: doBuild
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
@Override
protected ScriptedMetricAggregatorFactory doBuild(SearchContext context, AggregatorFactory<?> parent,
Builder subfactoriesBuilder) throws IOException {
QueryShardContext queryShardContext = context.getQueryShardContext();
Function<Map<String, Object>, ExecutableScript> executableInitScript;
if (initScript != null) {
executableInitScript = queryShardContext.getLazyExecutableScript(initScript, ScriptContext.Standard.AGGS);
} else {
executableInitScript = (p) -> null;
}
Function<Map<String, Object>, SearchScript> searchMapScript = queryShardContext.getLazySearchScript(mapScript,
ScriptContext.Standard.AGGS);
Function<Map<String, Object>, ExecutableScript> executableCombineScript;
if (combineScript != null) {
executableCombineScript = queryShardContext.getLazyExecutableScript(combineScript, ScriptContext.Standard.AGGS);
} else {
executableCombineScript = (p) -> null;
}
return new ScriptedMetricAggregatorFactory(name, searchMapScript, executableInitScript, executableCombineScript, reduceScript,
params, context, parent, subfactoriesBuilder, metaData);
}
示例7: resolveNested
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
protected static Nested resolveNested(QueryShardContext context, String nestedPath, QueryBuilder nestedFilter) throws IOException {
Nested nested = null;
if (nestedPath != null) {
BitSetProducer rootDocumentsFilter = context.bitsetFilter(Queries.newNonNestedFilter());
ObjectMapper nestedObjectMapper = context.getObjectMapper(nestedPath);
if (nestedObjectMapper == null) {
throw new QueryShardException(context, "[nested] failed to find nested object under path [" + nestedPath + "]");
}
if (!nestedObjectMapper.nested().isNested()) {
throw new QueryShardException(context, "[nested] nested object under path [" + nestedPath + "] is not of nested type");
}
Query innerDocumentsQuery;
if (nestedFilter != null) {
context.nestedScope().nextLevel(nestedObjectMapper);
innerDocumentsQuery = QueryBuilder.rewriteQuery(nestedFilter, context).toFilter(context);
context.nestedScope().previousLevel();
} else {
innerDocumentsQuery = nestedObjectMapper.nestedTypeFilter();
}
nested = new Nested(rootDocumentsFilter, innerDocumentsQuery);
}
return nested;
}
示例8: testRangeQuery
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
public void testRangeQuery() throws IOException {
Settings indexSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1).build();
QueryShardContext context = new QueryShardContext(0,
new IndexSettings(IndexMetaData.builder("foo").settings(indexSettings).build(), indexSettings),
null, null, null, null, null, xContentRegistry(), null, null, () -> nowInMillis);
MappedFieldType ft = createDefaultFieldType();
ft.setName("field");
String date1 = "2015-10-12T14:10:55";
String date2 = "2016-04-28T11:33:52";
long instant1 = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parser().parseDateTime(date1).getMillis();
long instant2 = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parser().parseDateTime(date2).getMillis() + 999;
ft.setIndexOptions(IndexOptions.DOCS);
Query expected = new IndexOrDocValuesQuery(
LongPoint.newRangeQuery("field", instant1, instant2),
SortedNumericDocValuesField.newRangeQuery("field", instant1, instant2));
assertEquals(expected,
ft.rangeQuery(date1, date2, true, true, context).rewrite(new MultiReader()));
ft.setIndexOptions(IndexOptions.NONE);
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> ft.rangeQuery(date1, date2, true, true, context));
assertEquals("Cannot search on field [field] since it is not indexed.", e.getMessage());
}
示例9: parseVariable
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
private AbstractDistanceScoreFunction parseVariable(String fieldName, XContentParser parser, QueryShardContext context,
MultiValueMode mode) throws IOException {
//the field must exist, else we cannot read the value for the doc later
MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType == null) {
throw new ParsingException(parser.getTokenLocation(), "unknown field [{}]", fieldName);
}
// dates and time and geo need special handling
parser.nextToken();
if (fieldType instanceof DateFieldMapper.DateFieldType) {
return parseDateVariable(parser, context, fieldType, mode);
} else if (fieldType instanceof GeoPointFieldType) {
return parseGeoVariable(parser, context, fieldType, mode);
} else if (fieldType instanceof NumberFieldMapper.NumberFieldType) {
return parseNumberVariable(parser, context, fieldType, mode);
} else {
throw new ParsingException(parser.getTokenLocation(), "field [{}] is of type [{}], but only numeric types are supported.",
fieldName, fieldType);
}
}
示例10: createAggregator
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
protected <A extends Aggregator, B extends AggregationBuilder> A createAggregator(B aggregationBuilder,
IndexSearcher indexSearcher,
MappedFieldType... fieldTypes) throws IOException {
IndexSettings indexSettings = createIndexSettings();
SearchContext searchContext = createSearchContext(indexSearcher, indexSettings);
CircuitBreakerService circuitBreakerService = new NoneCircuitBreakerService();
when(searchContext.bigArrays()).thenReturn(new MockBigArrays(Settings.EMPTY, circuitBreakerService));
// TODO: now just needed for top_hits, this will need to be revised for other agg unit tests:
MapperService mapperService = mapperServiceMock();
when(mapperService.hasNested()).thenReturn(false);
when(searchContext.mapperService()).thenReturn(mapperService);
IndexFieldDataService ifds = new IndexFieldDataService(indexSettings,
new IndicesFieldDataCache(Settings.EMPTY, new IndexFieldDataCache.Listener() {
}), circuitBreakerService, mapperService);
when(searchContext.fieldData()).thenReturn(ifds);
SearchLookup searchLookup = new SearchLookup(mapperService, ifds, new String[]{"type"});
when(searchContext.lookup()).thenReturn(searchLookup);
QueryShardContext queryShardContext = queryShardContextMock(fieldTypes, indexSettings, circuitBreakerService);
when(searchContext.getQueryShardContext()).thenReturn(queryShardContext);
@SuppressWarnings("unchecked")
A aggregator = (A) aggregationBuilder.build(searchContext, null).create(null, true);
return aggregator;
}
示例11: testUnmappedLong
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
public void testUnmappedLong() throws Exception {
IndexService indexService = createIndex("index", Settings.EMPTY, "type");
client().prepareIndex("index", "type", "1")
.setSource()
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.get();
try (Searcher searcher = indexService.getShard(0).acquireSearcher("test")) {
QueryShardContext context = indexService.newQueryShardContext(0, searcher.reader(), () -> 42L);
ValuesSourceConfig<ValuesSource.Numeric> config = ValuesSourceConfig.resolve(
context, ValueType.NUMBER, "long", null, null, null, null);
ValuesSource.Numeric valuesSource = config.toValuesSource(context);
assertNull(valuesSource);
config = ValuesSourceConfig.resolve(
context, ValueType.NUMBER, "long", null, 42, null, null);
valuesSource = config.toValuesSource(context);
LeafReaderContext ctx = searcher.reader().leaves().get(0);
SortedNumericDocValues values = valuesSource.longValues(ctx);
values.setDocument(0);
assertEquals(1, values.count());
assertEquals(42, values.valueAt(0));
}
}
示例12: rangeQuery
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper,
ShapeRelation relation, @Nullable DateTimeZone timeZone, @Nullable DateMathParser parser,
QueryShardContext context) {
DateTimeZone zone = (timeZone == null) ? DateTimeZone.UTC : timeZone;
DateMathParser dateMathParser = (parser == null) ?
new DateMathParser(DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER) : parser;
Long low = lowerTerm == null ? Long.MIN_VALUE :
dateMathParser.parse(lowerTerm instanceof BytesRef ? ((BytesRef) lowerTerm).utf8ToString() : lowerTerm.toString(),
context::nowInMillis, false, zone);
Long high = upperTerm == null ? Long.MAX_VALUE :
dateMathParser.parse(upperTerm instanceof BytesRef ? ((BytesRef) upperTerm).utf8ToString() : upperTerm.toString(),
context::nowInMillis, false, zone);
return super.rangeQuery(field, low, high, includeLower, includeUpper, relation, zone, dateMathParser, context);
}
示例13: getFieldNameToVisibilityMap
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
protected FieldNameToVisibilityMap getFieldNameToVisibilityMap(QueryShardContext context) {
Map<String, Object> elementMetadata = context.getMapperService().documentMapper(ELEMENT_DOCUMENT_MAPPER_NAME).meta();
if (elementMetadata == null) {
throw new NullPointerException("Could not find " + ELEMENT_DOCUMENT_MAPPER_NAME + " metadata");
}
Object memgraphMeta = elementMetadata.get("memgraph");
if (memgraphMeta == null) {
throw new NullPointerException("Could not find memgraph metadata in field mapping");
}
return FieldNameToVisibilityMap.createFrommemgraphMetadata(memgraphMeta);
}
示例14: ParserContext
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
public ParserContext(String type, IndexAnalyzers indexAnalyzers, Function<String, SimilarityProvider> similarityLookupService,
MapperService mapperService, Function<String, TypeParser> typeParsers,
Version indexVersionCreated, Supplier<QueryShardContext> queryShardContextSupplier) {
this.type = type;
this.indexAnalyzers = indexAnalyzers;
this.similarityLookupService = similarityLookupService;
this.mapperService = mapperService;
this.typeParsers = typeParsers;
this.indexVersionCreated = indexVersionCreated;
this.queryShardContextSupplier = queryShardContextSupplier;
}
示例15: testCommonCaseIsOptimized
import org.elasticsearch.index.query.QueryShardContext; //导入依赖的package包/类
public void testCommonCaseIsOptimized() throws IOException {
// make sure the below tests test something...
assertFalse(SortField.class.equals(LatLonDocValuesField.newDistanceSort("random_field_name", 3.5, 2.1).getClass()));
QueryShardContext context = createMockShardContext();
// The common case should use LatLonDocValuesField.newDistanceSort
GeoDistanceSortBuilder builder = new GeoDistanceSortBuilder("", new GeoPoint(3.5, 2.1));
SortFieldAndFormat sort = builder.build(context);
assertEquals(LatLonDocValuesField.newDistanceSort("random_field_name", 3.5, 2.1).getClass(), sort.field.getClass());
// however this might be disabled by fancy options
builder = new GeoDistanceSortBuilder("random_field_name", new GeoPoint(3.5, 2.1), new GeoPoint(3.0, 4));
sort = builder.build(context);
assertEquals(SortField.class, sort.field.getClass()); // 2 points -> plain SortField with a custom comparator
builder = new GeoDistanceSortBuilder("random_field_name", new GeoPoint(3.5, 2.1));
builder.unit(DistanceUnit.KILOMETERS);
sort = builder.build(context);
assertEquals(SortField.class, sort.field.getClass()); // km rather than m -> plain SortField with a custom comparator
builder = new GeoDistanceSortBuilder("random_field_name", new GeoPoint(3.5, 2.1));
builder.order(SortOrder.DESC);
sort = builder.build(context);
assertEquals(SortField.class, sort.field.getClass()); // descending means the max value should be considered rather than min
builder = new GeoDistanceSortBuilder("random_field_name", new GeoPoint(3.5, 2.1));
builder.setNestedPath("some_nested_path");
sort = builder.build(context);
assertEquals(SortField.class, sort.field.getClass()); // can't use LatLon optimized sorting with nested fields
builder = new GeoDistanceSortBuilder("random_field_name", new GeoPoint(3.5, 2.1));
builder.order(SortOrder.DESC);
sort = builder.build(context);
assertEquals(SortField.class, sort.field.getClass()); // can't use LatLon optimized sorting with DESC sorting
}