Search in sources :

Example 11 with Text

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.text.Text in project elasticsearch by elastic.

the class SearchAfterBuilderTests method randomSearchAfterBuilder.

private static SearchAfterBuilder randomSearchAfterBuilder() throws IOException {
    int numSearchFrom = randomIntBetween(1, 10);
    SearchAfterBuilder searchAfterBuilder = new SearchAfterBuilder();
    Object[] values = new Object[numSearchFrom];
    for (int i = 0; i < numSearchFrom; i++) {
        int branch = randomInt(9);
        switch(branch) {
            case 0:
                values[i] = randomInt();
                break;
            case 1:
                values[i] = randomFloat();
                break;
            case 2:
                values[i] = randomLong();
                break;
            case 3:
                values[i] = randomDouble();
                break;
            case 4:
                values[i] = randomAsciiOfLengthBetween(5, 20);
                break;
            case 5:
                values[i] = randomBoolean();
                break;
            case 6:
                values[i] = randomByte();
                break;
            case 7:
                values[i] = randomShort();
                break;
            case 8:
                values[i] = new Text(randomAsciiOfLengthBetween(5, 20));
                break;
            case 9:
                values[i] = null;
                break;
        }
    }
    searchAfterBuilder.setSortValues(values);
    return searchAfterBuilder;
}
Also used : Text(org.elasticsearch.common.text.Text) GeoPoint(org.elasticsearch.common.geo.GeoPoint)

Example 12 with Text

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.text.Text in project elasticsearch by elastic.

the class SuggestionOptionTests method testToXContent.

public void testToXContent() throws IOException {
    Option option = new Option(new Text("someText"), new Text("somethingHighlighted"), 1.3f, true);
    BytesReference xContent = toXContent(option, XContentType.JSON, randomBoolean());
    assertEquals("{\"text\":\"someText\"," + "\"highlighted\":\"somethingHighlighted\"," + "\"score\":1.3," + "\"collate_match\":true" + "}", xContent.utf8ToString());
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) Option(org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option) Text(org.elasticsearch.common.text.Text)

Example 13 with Text

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.text.Text in project elasticsearch by elastic.

the class CompletionSuggestionOptionTests method testToXContent.

public void testToXContent() throws IOException {
    Map<String, Set<CharSequence>> contexts = Collections.singletonMap("key", Collections.singleton("value"));
    CompletionSuggestion.Entry.Option option = new CompletionSuggestion.Entry.Option(1, new Text("someText"), 1.3f, contexts);
    BytesReference xContent = toXContent(option, XContentType.JSON, randomBoolean());
    assertEquals("{\"text\":\"someText\",\"score\":1.3,\"contexts\":{\"key\":[\"value\"]}}", xContent.utf8ToString());
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) CompletionSuggestion(org.elasticsearch.search.suggest.completion.CompletionSuggestion) Set(java.util.Set) HashSet(java.util.HashSet) Option(org.elasticsearch.search.suggest.completion.CompletionSuggestion.Entry.Option) Option(org.elasticsearch.search.suggest.completion.CompletionSuggestion.Entry.Option) Text(org.elasticsearch.common.text.Text)

Example 14 with Text

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.text.Text in project elasticsearch by elastic.

the class RandomSearchRequestGenerator method randomSearchSourceBuilder.

public static SearchSourceBuilder randomSearchSourceBuilder(Supplier<HighlightBuilder> randomHighlightBuilder, Supplier<SuggestBuilder> randomSuggestBuilder, Supplier<RescoreBuilder<?>> randomRescoreBuilder, Supplier<List<SearchExtBuilder>> randomExtBuilders, Supplier<CollapseBuilder> randomCollapseBuilder) {
    SearchSourceBuilder builder = new SearchSourceBuilder();
    if (randomBoolean()) {
        builder.from(randomIntBetween(0, 10000));
    }
    if (randomBoolean()) {
        builder.size(randomIntBetween(0, 10000));
    }
    if (randomBoolean()) {
        builder.explain(randomBoolean());
    }
    if (randomBoolean()) {
        builder.version(randomBoolean());
    }
    if (randomBoolean()) {
        builder.trackScores(randomBoolean());
    }
    if (randomBoolean()) {
        builder.minScore(randomFloat() * 1000);
    }
    if (randomBoolean()) {
        builder.timeout(TimeValue.parseTimeValue(randomTimeValue(), null, "timeout"));
    }
    if (randomBoolean()) {
        builder.terminateAfter(randomIntBetween(1, 100000));
    }
    switch(randomInt(2)) {
        case 0:
            builder.storedFields();
            break;
        case 1:
            builder.storedField("_none_");
            break;
        case 2:
            int fieldsSize = randomInt(25);
            List<String> fields = new ArrayList<>(fieldsSize);
            for (int i = 0; i < fieldsSize; i++) {
                fields.add(randomAsciiOfLengthBetween(5, 50));
            }
            builder.storedFields(fields);
            break;
        default:
            throw new IllegalStateException();
    }
    if (randomBoolean()) {
        int scriptFieldsSize = randomInt(25);
        for (int i = 0; i < scriptFieldsSize; i++) {
            if (randomBoolean()) {
                builder.scriptField(randomAsciiOfLengthBetween(5, 50), new Script("foo"), randomBoolean());
            } else {
                builder.scriptField(randomAsciiOfLengthBetween(5, 50), new Script("foo"));
            }
        }
    }
    if (randomBoolean()) {
        FetchSourceContext fetchSourceContext;
        int branch = randomInt(5);
        String[] includes = new String[randomIntBetween(0, 20)];
        for (int i = 0; i < includes.length; i++) {
            includes[i] = randomAsciiOfLengthBetween(5, 20);
        }
        String[] excludes = new String[randomIntBetween(0, 20)];
        for (int i = 0; i < excludes.length; i++) {
            excludes[i] = randomAsciiOfLengthBetween(5, 20);
        }
        switch(branch) {
            case 0:
                fetchSourceContext = new FetchSourceContext(randomBoolean());
                break;
            case 1:
                fetchSourceContext = new FetchSourceContext(true, includes, excludes);
                break;
            case 2:
                fetchSourceContext = new FetchSourceContext(true, new String[] { randomAsciiOfLengthBetween(5, 20) }, new String[] { randomAsciiOfLengthBetween(5, 20) });
                break;
            case 3:
                fetchSourceContext = new FetchSourceContext(true, includes, excludes);
                break;
            case 4:
                fetchSourceContext = new FetchSourceContext(true, includes, null);
                break;
            case 5:
                fetchSourceContext = new FetchSourceContext(true, new String[] { randomAsciiOfLengthBetween(5, 20) }, null);
                break;
            default:
                throw new IllegalStateException();
        }
        builder.fetchSource(fetchSourceContext);
    }
    if (randomBoolean()) {
        int size = randomIntBetween(0, 20);
        List<String> statsGroups = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            statsGroups.add(randomAsciiOfLengthBetween(5, 20));
        }
        builder.stats(statsGroups);
    }
    if (randomBoolean()) {
        int indexBoostSize = randomIntBetween(1, 10);
        for (int i = 0; i < indexBoostSize; i++) {
            builder.indexBoost(randomAsciiOfLengthBetween(5, 20), randomFloat() * 10);
        }
    }
    if (randomBoolean()) {
        builder.query(QueryBuilders.termQuery(randomAsciiOfLengthBetween(5, 20), randomAsciiOfLengthBetween(5, 20)));
    }
    if (randomBoolean()) {
        builder.postFilter(QueryBuilders.termQuery(randomAsciiOfLengthBetween(5, 20), randomAsciiOfLengthBetween(5, 20)));
    }
    if (randomBoolean()) {
        int numSorts = randomIntBetween(1, 5);
        for (int i = 0; i < numSorts; i++) {
            int branch = randomInt(5);
            switch(branch) {
                case 0:
                    builder.sort(SortBuilders.fieldSort(randomAsciiOfLengthBetween(5, 20)).order(randomFrom(SortOrder.values())));
                    break;
                case 1:
                    builder.sort(SortBuilders.geoDistanceSort(randomAsciiOfLengthBetween(5, 20), AbstractQueryTestCase.randomGeohash(1, 12)).order(randomFrom(SortOrder.values())));
                    break;
                case 2:
                    builder.sort(SortBuilders.scoreSort().order(randomFrom(SortOrder.values())));
                    break;
                case 3:
                    builder.sort(SortBuilders.scriptSort(new Script("foo"), ScriptSortBuilder.ScriptSortType.NUMBER).order(randomFrom(SortOrder.values())));
                    break;
                case 4:
                    builder.sort(randomAsciiOfLengthBetween(5, 20));
                    break;
                case 5:
                    builder.sort(randomAsciiOfLengthBetween(5, 20), randomFrom(SortOrder.values()));
                    break;
            }
        }
    }
    if (randomBoolean()) {
        int numSearchFrom = randomIntBetween(1, 5);
        try {
            // We build a json version of the search_from first in order to
            // ensure that every number type remain the same before/after xcontent (de)serialization.
            // This is not a problem because the final type of each field value is extracted from associated sort field.
            // This little trick ensure that equals and hashcode are the same when using the xcontent serialization.
            XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
            jsonBuilder.startObject();
            jsonBuilder.startArray("search_from");
            for (int i = 0; i < numSearchFrom; i++) {
                int branch = randomInt(8);
                switch(branch) {
                    case 0:
                        jsonBuilder.value(randomInt());
                        break;
                    case 1:
                        jsonBuilder.value(randomFloat());
                        break;
                    case 2:
                        jsonBuilder.value(randomLong());
                        break;
                    case 3:
                        jsonBuilder.value(randomDouble());
                        break;
                    case 4:
                        jsonBuilder.value(randomAsciiOfLengthBetween(5, 20));
                        break;
                    case 5:
                        jsonBuilder.value(randomBoolean());
                        break;
                    case 6:
                        jsonBuilder.value(randomByte());
                        break;
                    case 7:
                        jsonBuilder.value(randomShort());
                        break;
                    case 8:
                        jsonBuilder.value(new Text(randomAsciiOfLengthBetween(5, 20)));
                        break;
                }
            }
            jsonBuilder.endArray();
            jsonBuilder.endObject();
            XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(NamedXContentRegistry.EMPTY, jsonBuilder.bytes());
            parser.nextToken();
            parser.nextToken();
            parser.nextToken();
            builder.searchAfter(SearchAfterBuilder.fromXContent(parser).getSortValues());
        } catch (IOException e) {
            throw new RuntimeException("Error building search_from", e);
        }
    }
    if (randomBoolean()) {
        builder.highlighter(randomHighlightBuilder.get());
    }
    if (randomBoolean()) {
        builder.suggest(randomSuggestBuilder.get());
    }
    if (randomBoolean()) {
        int numRescores = randomIntBetween(1, 5);
        for (int i = 0; i < numRescores; i++) {
            builder.addRescorer(randomRescoreBuilder.get());
        }
    }
    if (randomBoolean()) {
        builder.aggregation(AggregationBuilders.avg(randomAsciiOfLengthBetween(5, 20)));
    }
    if (randomBoolean()) {
        builder.ext(randomExtBuilders.get());
    }
    if (randomBoolean()) {
        String field = randomBoolean() ? null : randomAsciiOfLengthBetween(5, 20);
        int max = between(2, 1000);
        int id = randomInt(max - 1);
        if (field == null) {
            builder.slice(new SliceBuilder(id, max));
        } else {
            builder.slice(new SliceBuilder(field, id, max));
        }
    }
    if (randomBoolean()) {
        builder.collapse(randomCollapseBuilder.get());
    }
    return builder;
}
Also used : Script(org.elasticsearch.script.Script) ArrayList(java.util.ArrayList) Text(org.elasticsearch.common.text.Text) IOException(java.io.IOException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) SliceBuilder(org.elasticsearch.search.slice.SliceBuilder) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 15 with Text

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.common.text.Text in project elasticsearch by elastic.

the class BaseXContentTestCase method testObject.

public void testObject() throws Exception {
    Map<String, Object> object = new HashMap<>();
    object.put("{'object':false}", Boolean.FALSE);
    object.put("{'object':13}", (byte) 13);
    object.put("{'object':5.0}", 5.0d);
    object.put("{'object':8.0}", 8.0f);
    object.put("{'object':{'lat':45.759429931640625,'lon':4.8394775390625}}", GeoPoint.fromGeohash("u05kq4k"));
    object.put("{'object':3}", 3);
    object.put("{'object':2}", 2L);
    object.put("{'object':1}", (short) 1);
    object.put("{'object':'string'}", "string");
    object.put("{'object':'a'}", new Text("a"));
    object.put("{'object':'b'}", new Text(new BytesArray("b")));
    object.put("{'object':null}", null);
    object.put("{'object':'OPEN'}", IndexMetaData.State.OPEN);
    object.put("{'object':'NM'}", DistanceUnit.NAUTICALMILES);
    object.put("{'object':{'f1':'v1'}}", singletonMap("f1", "v1"));
    object.put("{'object':{'f1':{'f2':'v2'}}}", singletonMap("f1", singletonMap("f2", "v2")));
    object.put("{'object':[1,2,3]}", Arrays.asList(1, 2, 3));
    final String path = Constants.WINDOWS ? "{'object':'a\\\\b\\\\c'}" : "{'object':'a/b/c'}";
    object.put(path, PathUtils.get("a", "b", "c"));
    final DateTimeFormatter formatter = XContentBuilder.DEFAULT_DATE_PRINTER;
    final Date d1 = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC).toDate();
    object.put("{'object':'" + formatter.print(d1.getTime()) + "'}", d1);
    final DateTime d2 = DateTime.now();
    object.put("{'object':'" + formatter.print(d2) + "'}", d2);
    final Calendar c1 = new DateTime(2010, 1, 1, 0, 0, DateTimeZone.UTC).toCalendar(Locale.ROOT);
    object.put("{'object':'2010-01-01T00:00:00.000Z'}", c1);
    final ToXContent x1 = (builder, params) -> builder.startObject().field("f1", "v1").field("f2", 2).array("f3", 3, 4, 5).endObject();
    final ToXContent x2 = (builder, params) -> builder.startObject().field("f1", "v1").field("f2", x1).endObject();
    object.put("{'object':{'f1':'v1','f2':{'f1':'v1','f2':2,'f3':[3,4,5]}}}", x2);
    for (Map.Entry<String, Object> o : object.entrySet()) {
        final String expected = o.getKey();
        assertResult(expected, () -> builder().humanReadable(true).startObject().field("object", o.getValue()).endObject());
        assertResult(expected, () -> builder().humanReadable(true).startObject().field("object").value(o.getValue()).endObject());
    }
    assertResult("{'objects':[null,null,null]}", () -> builder().startObject().array("objects", null, null, null).endObject());
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) DateTimeZone(org.joda.time.DateTimeZone) Arrays(java.util.Arrays) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) Date(java.util.Date) HashMap(java.util.HashMap) Strings(org.elasticsearch.common.Strings) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) Calendar(java.util.Calendar) ByteArrayInputStream(java.io.ByteArrayInputStream) Text(org.elasticsearch.common.text.Text) Locale(java.util.Locale) Map(java.util.Map) GeoPoint(org.elasticsearch.common.geo.GeoPoint) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException) BigInteger(java.math.BigInteger) Collections.singletonMap(java.util.Collections.singletonMap) ESTestCase(org.elasticsearch.test.ESTestCase) ParseField(org.elasticsearch.common.ParseField) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Path(java.nio.file.Path) PathUtils(org.elasticsearch.common.io.PathUtils) ISODateTimeFormat(org.joda.time.format.ISODateTimeFormat) Collections.emptyMap(java.util.Collections.emptyMap) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) BytesRef(org.apache.lucene.util.BytesRef) Matchers.allOf(org.hamcrest.Matchers.allOf) DateTime(org.joda.time.DateTime) Matchers(org.hamcrest.Matchers) ReadableInstant(org.joda.time.ReadableInstant) IOException(java.io.IOException) BytesReference(org.elasticsearch.common.bytes.BytesReference) Matchers.startsWith(org.hamcrest.Matchers.startsWith) TimeUnit(java.util.concurrent.TimeUnit) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) Constants(org.apache.lucene.util.Constants) DistanceUnit(org.elasticsearch.common.unit.DistanceUnit) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Token(org.elasticsearch.common.xcontent.XContentParser.Token) Matcher(org.hamcrest.Matcher) Instant(org.joda.time.Instant) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Collections(java.util.Collections) Matchers.containsString(org.hamcrest.Matchers.containsString) BytesArray(org.elasticsearch.common.bytes.BytesArray) HashMap(java.util.HashMap) Calendar(java.util.Calendar) Text(org.elasticsearch.common.text.Text) Matchers.containsString(org.hamcrest.Matchers.containsString) Date(java.util.Date) DateTime(org.joda.time.DateTime) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) HashMap(java.util.HashMap) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) Collections.emptyMap(java.util.Collections.emptyMap)

Aggregations

Text (org.elasticsearch.common.text.Text)50 SearchHit (org.elasticsearch.search.SearchHit)13 ArrayList (java.util.ArrayList)12 HashMap (java.util.HashMap)12 Map (java.util.Map)10 SearchHits (org.elasticsearch.search.SearchHits)10 IOException (java.io.IOException)9 BytesReference (org.elasticsearch.common.bytes.BytesReference)9 BytesArray (org.elasticsearch.common.bytes.BytesArray)7 CompletionSuggestion (org.elasticsearch.search.suggest.completion.CompletionSuggestion)7 List (java.util.List)6 Test (org.junit.Test)6 SearchResponse (org.elasticsearch.action.search.SearchResponse)5 SearchHitField (org.elasticsearch.search.SearchHitField)5 HighlightField (org.elasticsearch.search.fetch.subphase.highlight.HighlightField)5 Option (org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 BytesRef (org.apache.lucene.util.BytesRef)4 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)4 InternalSearchResponse (org.elasticsearch.search.internal.InternalSearchResponse)4