Search in sources :

Example 6 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class CandidateQueryTests method testRangeQueries.

public void testRangeQueries() throws Exception {
    List<ParseContext.Document> docs = new ArrayList<>();
    addQuery(IntPoint.newRangeQuery("int_field", 0, 5), docs);
    addQuery(LongPoint.newRangeQuery("long_field", 5L, 10L), docs);
    addQuery(HalfFloatPoint.newRangeQuery("half_float_field", 10, 15), docs);
    addQuery(FloatPoint.newRangeQuery("float_field", 15, 20), docs);
    addQuery(DoublePoint.newRangeQuery("double_field", 20, 25), docs);
    addQuery(InetAddressPoint.newRangeQuery("ip_field", forString("192.168.0.1"), forString("192.168.0.10")), docs);
    indexWriter.addDocuments(docs);
    indexWriter.close();
    directoryReader = DirectoryReader.open(directory);
    IndexSearcher shardSearcher = newSearcher(directoryReader);
    shardSearcher.setQueryCache(null);
    Version v = VersionUtils.randomIndexCompatibleVersion(random());
    MemoryIndex memoryIndex = MemoryIndex.fromDocument(Collections.singleton(new IntPoint("int_field", 3)), new WhitespaceAnalyzer());
    IndexSearcher percolateSearcher = memoryIndex.createSearcher();
    Query query = fieldType.percolateQuery("_name", queryStore, Collections.singletonList(new BytesArray("{}")), percolateSearcher, false, v);
    TopDocs topDocs = shardSearcher.search(query, 1);
    assertEquals(1L, topDocs.totalHits.value);
    assertEquals(1, topDocs.scoreDocs.length);
    assertEquals(0, topDocs.scoreDocs[0].doc);
    memoryIndex = MemoryIndex.fromDocument(Collections.singleton(new LongPoint("long_field", 7L)), new WhitespaceAnalyzer());
    percolateSearcher = memoryIndex.createSearcher();
    query = fieldType.percolateQuery("_name", queryStore, Collections.singletonList(new BytesArray("{}")), percolateSearcher, false, v);
    topDocs = shardSearcher.search(query, 1);
    assertEquals(1L, topDocs.totalHits.value);
    assertEquals(1, topDocs.scoreDocs.length);
    assertEquals(1, topDocs.scoreDocs[0].doc);
    memoryIndex = MemoryIndex.fromDocument(Collections.singleton(new HalfFloatPoint("half_float_field", 12)), new WhitespaceAnalyzer());
    percolateSearcher = memoryIndex.createSearcher();
    query = fieldType.percolateQuery("_name", queryStore, Collections.singletonList(new BytesArray("{}")), percolateSearcher, false, v);
    topDocs = shardSearcher.search(query, 1);
    assertEquals(1L, topDocs.totalHits.value);
    assertEquals(1, topDocs.scoreDocs.length);
    assertEquals(2, topDocs.scoreDocs[0].doc);
    memoryIndex = MemoryIndex.fromDocument(Collections.singleton(new FloatPoint("float_field", 17)), new WhitespaceAnalyzer());
    percolateSearcher = memoryIndex.createSearcher();
    query = fieldType.percolateQuery("_name", queryStore, Collections.singletonList(new BytesArray("{}")), percolateSearcher, false, v);
    topDocs = shardSearcher.search(query, 1);
    assertEquals(1, topDocs.totalHits.value);
    assertEquals(1, topDocs.scoreDocs.length);
    assertEquals(3, topDocs.scoreDocs[0].doc);
    memoryIndex = MemoryIndex.fromDocument(Collections.singleton(new DoublePoint("double_field", 21)), new WhitespaceAnalyzer());
    percolateSearcher = memoryIndex.createSearcher();
    query = fieldType.percolateQuery("_name", queryStore, Collections.singletonList(new BytesArray("{}")), percolateSearcher, false, v);
    topDocs = shardSearcher.search(query, 1);
    assertEquals(1, topDocs.totalHits.value);
    assertEquals(1, topDocs.scoreDocs.length);
    assertEquals(4, topDocs.scoreDocs[0].doc);
    memoryIndex = MemoryIndex.fromDocument(Collections.singleton(new InetAddressPoint("ip_field", forString("192.168.0.4"))), new WhitespaceAnalyzer());
    percolateSearcher = memoryIndex.createSearcher();
    query = fieldType.percolateQuery("_name", queryStore, Collections.singletonList(new BytesArray("{}")), percolateSearcher, false, v);
    topDocs = shardSearcher.search(query, 1);
    assertEquals(1, topDocs.totalHits.value);
    assertEquals(1, topDocs.scoreDocs.length);
    assertEquals(5, topDocs.scoreDocs[0].doc);
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) WhitespaceAnalyzer(org.apache.lucene.analysis.core.WhitespaceAnalyzer) BytesArray(org.opensearch.common.bytes.BytesArray) Query(org.apache.lucene.search.Query) PhraseQuery(org.apache.lucene.search.PhraseQuery) BlendedTermQuery(org.apache.lucene.queries.BlendedTermQuery) CoveringQuery(org.apache.lucene.search.CoveringQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) SpanNotQuery(org.apache.lucene.search.spans.SpanNotQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) SpanNearQuery(org.apache.lucene.search.spans.SpanNearQuery) SpanOrQuery(org.apache.lucene.search.spans.SpanOrQuery) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) CommonTermsQuery(org.apache.lucene.queries.CommonTermsQuery) FunctionScoreQuery(org.opensearch.common.lucene.search.function.FunctionScoreQuery) TermInSetQuery(org.apache.lucene.search.TermInSetQuery) PrefixQuery(org.apache.lucene.search.PrefixQuery) DisjunctionMaxQuery(org.apache.lucene.search.DisjunctionMaxQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) InetAddressPoint(org.apache.lucene.document.InetAddressPoint) ArrayList(java.util.ArrayList) LongPoint(org.apache.lucene.document.LongPoint) Document(org.apache.lucene.document.Document) TopDocs(org.apache.lucene.search.TopDocs) HalfFloatPoint(org.apache.lucene.document.HalfFloatPoint) IntPoint(org.apache.lucene.document.IntPoint) MemoryIndex(org.apache.lucene.index.memory.MemoryIndex) FloatPoint(org.apache.lucene.document.FloatPoint) HalfFloatPoint(org.apache.lucene.document.HalfFloatPoint) Version(org.opensearch.Version) DoublePoint(org.apache.lucene.document.DoublePoint)

Example 7 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class QueryBuilderStoreTests method testStoringQueryBuilders.

public void testStoringQueryBuilders() throws IOException {
    try (Directory directory = newDirectory()) {
        TermQueryBuilder[] queryBuilders = new TermQueryBuilder[randomIntBetween(1, 16)];
        IndexWriterConfig config = new IndexWriterConfig(new WhitespaceAnalyzer());
        config.setMergePolicy(NoMergePolicy.INSTANCE);
        Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build();
        BinaryFieldMapper fieldMapper = PercolatorFieldMapper.Builder.createQueryBuilderFieldBuilder(new Mapper.BuilderContext(settings, new ContentPath(0)));
        Version version = Version.CURRENT;
        try (IndexWriter indexWriter = new IndexWriter(directory, config)) {
            for (int i = 0; i < queryBuilders.length; i++) {
                queryBuilders[i] = new TermQueryBuilder(randomAlphaOfLength(4), randomAlphaOfLength(8));
                ParseContext parseContext = mock(ParseContext.class);
                ParseContext.Document document = new ParseContext.Document();
                when(parseContext.doc()).thenReturn(document);
                PercolatorFieldMapper.createQueryBuilderField(version, fieldMapper, queryBuilders[i], parseContext);
                indexWriter.addDocument(document);
            }
        }
        QueryShardContext queryShardContext = mock(QueryShardContext.class);
        when(queryShardContext.indexVersionCreated()).thenReturn(version);
        when(queryShardContext.getWriteableRegistry()).thenReturn(writableRegistry());
        when(queryShardContext.getXContentRegistry()).thenReturn(xContentRegistry());
        when(queryShardContext.getForField(fieldMapper.fieldType())).thenReturn(new BytesBinaryIndexFieldData(fieldMapper.name(), CoreValuesSourceType.BYTES));
        when(queryShardContext.fieldMapper(Mockito.anyString())).thenAnswer(invocation -> {
            final String fieldName = (String) invocation.getArguments()[0];
            return new KeywordFieldMapper.KeywordFieldType(fieldName);
        });
        PercolateQuery.QueryStore queryStore = PercolateQueryBuilder.createStore(fieldMapper.fieldType(), queryShardContext);
        try (IndexReader indexReader = DirectoryReader.open(directory)) {
            LeafReaderContext leafContext = indexReader.leaves().get(0);
            CheckedFunction<Integer, Query, IOException> queries = queryStore.getQueries(leafContext);
            assertEquals(queryBuilders.length, leafContext.reader().numDocs());
            for (int i = 0; i < queryBuilders.length; i++) {
                TermQuery query = (TermQuery) queries.apply(i);
                assertEquals(queryBuilders[i].fieldName(), query.getTerm().field());
                assertEquals(queryBuilders[i].value(), query.getTerm().text());
            }
        }
    }
}
Also used : BytesBinaryIndexFieldData(org.opensearch.index.fielddata.plain.BytesBinaryIndexFieldData) Query(org.apache.lucene.search.Query) TermQuery(org.apache.lucene.search.TermQuery) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) BinaryFieldMapper(org.opensearch.index.mapper.BinaryFieldMapper) KeywordFieldMapper(org.opensearch.index.mapper.KeywordFieldMapper) Mapper(org.opensearch.index.mapper.Mapper) Version(org.opensearch.Version) QueryShardContext(org.opensearch.index.query.QueryShardContext) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) Settings(org.opensearch.common.settings.Settings) Directory(org.apache.lucene.store.Directory) WhitespaceAnalyzer(org.apache.lucene.analysis.core.WhitespaceAnalyzer) TermQuery(org.apache.lucene.search.TermQuery) ContentPath(org.opensearch.index.mapper.ContentPath) IOException(java.io.IOException) IndexWriter(org.apache.lucene.index.IndexWriter) ParseContext(org.opensearch.index.mapper.ParseContext) IndexReader(org.apache.lucene.index.IndexReader) BinaryFieldMapper(org.opensearch.index.mapper.BinaryFieldMapper) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig)

Example 8 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class PercolatorFieldMapper method processQuery.

void processQuery(Query query, ParseContext context) {
    ParseContext.Document doc = context.doc();
    PercolatorFieldType pft = (PercolatorFieldType) this.fieldType();
    QueryAnalyzer.Result result;
    Version indexVersion = context.mapperService().getIndexSettings().getIndexVersionCreated();
    result = QueryAnalyzer.analyze(query, indexVersion);
    if (result == QueryAnalyzer.Result.UNKNOWN) {
        doc.add(new Field(pft.extractionResultField.name(), EXTRACTION_FAILED, INDEXED_KEYWORD));
        return;
    }
    for (QueryAnalyzer.QueryExtraction extraction : result.extractions) {
        if (extraction.term != null) {
            BytesRefBuilder builder = new BytesRefBuilder();
            builder.append(new BytesRef(extraction.field()));
            builder.append(FIELD_VALUE_SEPARATOR);
            builder.append(extraction.bytes());
            doc.add(new Field(queryTermsField.name(), builder.toBytesRef(), INDEXED_KEYWORD));
        } else if (extraction.range != null) {
            byte[] min = extraction.range.lowerPoint;
            byte[] max = extraction.range.upperPoint;
            doc.add(new BinaryRange(rangeFieldMapper.name(), encodeRange(extraction.range.fieldName, min, max)));
        }
    }
    if (result.matchAllDocs) {
        doc.add(new Field(extractionResultField.name(), EXTRACTION_FAILED, INDEXED_KEYWORD));
        if (result.verified) {
            doc.add(new Field(extractionResultField.name(), EXTRACTION_COMPLETE, INDEXED_KEYWORD));
        }
    } else if (result.verified) {
        doc.add(new Field(extractionResultField.name(), EXTRACTION_COMPLETE, INDEXED_KEYWORD));
    } else {
        doc.add(new Field(extractionResultField.name(), EXTRACTION_PARTIAL, INDEXED_KEYWORD));
    }
    createFieldNamesField(context);
    doc.add(new NumericDocValuesField(minimumShouldMatchFieldMapper.name(), result.minimumShouldMatch));
}
Also used : NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) Field(org.apache.lucene.document.Field) BytesRefBuilder(org.apache.lucene.util.BytesRefBuilder) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) Version(org.opensearch.Version) ParseContext(org.opensearch.index.mapper.ParseContext) BinaryRange(org.apache.lucene.document.BinaryRange) BytesRef(org.apache.lucene.util.BytesRef)

Example 9 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class RecoveryIT method testRecoveryClosedIndex.

/**
 * This test creates an index in the non upgraded cluster and closes it. It then checks that the index
 * is effectively closed and potentially replicated (if the version the index was created on supports
 * the replication of closed indices) during the rolling upgrade.
 */
public void testRecoveryClosedIndex() throws Exception {
    final String indexName = "closed_index_created_on_old";
    if (CLUSTER_TYPE == ClusterType.OLD) {
        createIndex(indexName, Settings.builder().put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1).put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 1).put(INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), "100ms").put(SETTING_ALLOCATION_MAX_RETRY.getKey(), // fail faster
        "0").build());
        ensureGreen(indexName);
        closeIndex(indexName);
    }
    final Version indexVersionCreated = indexVersionCreated(indexName);
    if (indexVersionCreated.onOrAfter(LegacyESVersion.V_7_2_0)) {
        // index was created on a version that supports the replication of closed indices,
        // so we expect the index to be closed and replicated
        ensureGreen(indexName);
        assertClosedIndex(indexName, true);
    } else {
        assertClosedIndex(indexName, false);
    }
}
Also used : Version(org.opensearch.Version) LegacyESVersion(org.opensearch.LegacyESVersion)

Example 10 with Version

use of org.opensearch.Version in project OpenSearch by opensearch-project.

the class RecoveryIT method testAutoExpandIndicesDuringRollingUpgrade.

public void testAutoExpandIndicesDuringRollingUpgrade() throws Exception {
    final String indexName = "test-auto-expand-filtering";
    final Version minimumNodeVersion = minimumNodeVersion();
    Response response = client().performRequest(new Request("GET", "_nodes"));
    ObjectPath objectPath = ObjectPath.createFromResponse(response);
    final Map<String, Object> nodeMap = objectPath.evaluate("nodes");
    List<String> nodes = new ArrayList<>(nodeMap.keySet());
    if (CLUSTER_TYPE == ClusterType.OLD) {
        createIndex(indexName, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, randomInt(2)).put(IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS, "0-all").build());
        ensureGreen(indexName);
        updateIndexSettings(indexName, Settings.builder().put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_PREFIX + "._id", nodes.get(randomInt(2))));
    }
    final int numberOfReplicas = Integer.parseInt(getIndexSettingsAsMap(indexName).get(IndexMetadata.SETTING_NUMBER_OF_REPLICAS).toString());
    if (minimumNodeVersion.onOrAfter(LegacyESVersion.V_7_6_0)) {
        assertEquals(nodes.size() - 2, numberOfReplicas);
        ensureGreen(indexName);
    } else {
        assertEquals(nodes.size() - 1, numberOfReplicas);
    }
}
Also used : Response(org.opensearch.client.Response) ObjectPath(org.opensearch.test.rest.yaml.ObjectPath) Version(org.opensearch.Version) LegacyESVersion(org.opensearch.LegacyESVersion) Request(org.opensearch.client.Request) ArrayList(java.util.ArrayList)

Aggregations

Version (org.opensearch.Version)242 Settings (org.opensearch.common.settings.Settings)86 LegacyESVersion (org.opensearch.LegacyESVersion)84 ArrayList (java.util.ArrayList)59 IOException (java.io.IOException)54 List (java.util.List)54 Map (java.util.Map)50 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)42 Collections (java.util.Collections)39 HashMap (java.util.HashMap)38 ClusterState (org.opensearch.cluster.ClusterState)38 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)37 HashSet (java.util.HashSet)36 BytesReference (org.opensearch.common.bytes.BytesReference)36 TimeValue (org.opensearch.common.unit.TimeValue)36 Set (java.util.Set)35 Collectors (java.util.stream.Collectors)34 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)33 StreamInput (org.opensearch.common.io.stream.StreamInput)32 BytesArray (org.opensearch.common.bytes.BytesArray)30