Ejemplo n.º 1
0
        /// <summary>
        /// Sort a single partition in-memory. </summary>
        private FileInfo SortPartition(int len) // LUCENENET NOTE: made private, since protected is not valid in a sealed class
        {
            var      data     = this.buffer;
            FileInfo tempFile = FileSupport.CreateTempFile("sort", "partition", DefaultTempDir());

            long start = Environment.TickCount;

            sortInfo.SortTime += (Environment.TickCount - start);

            using (var @out = new ByteSequencesWriter(tempFile))
            {
                BytesRef spare;

                IBytesRefIterator iter = buffer.GetIterator(comparer);
                while ((spare = iter.Next()) != null)
                {
                    Debug.Assert(spare.Length <= ushort.MaxValue);
                    @out.Write(spare);
                }
            }

            // Clean up the buffer for the next partition.
            data.Clear();
            return(tempFile);
        }
Ejemplo n.º 2
0
        private void Check(IBytesRefSorter sorter)
        {
            for (int i = 0; i < 100; i++)
            {
                byte[] current = new byte[Random.nextInt(256)];
                Random.NextBytes(current);
                sorter.Add(new BytesRef(current));
            }

            // Create two iterators and check that they're aligned with each other.
            IBytesRefIterator i1 = sorter.GetIterator();
            IBytesRefIterator i2 = sorter.GetIterator();

            // Verify sorter contract.
            try
            {
                sorter.Add(new BytesRef(new byte[1]));
                fail("expected contract violation.");
            }
            catch (InvalidOperationException /*e*/)
            {
                // Expected.
            }
            BytesRef spare1;
            BytesRef spare2;

            while ((spare1 = i1.Next()) != null && (spare2 = i2.Next()) != null)
            {
                assertEquals(spare1, spare2);
            }
            assertNull(i1.Next());
            assertNull(i2.Next());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Builds the final automaton from a list of entries.
        /// </summary>
        private FST <object> BuildAutomaton(IBytesRefSorter sorter)
        {
            // Build the automaton.
            Outputs <object> outputs = NoOutputs.Singleton;
            object           empty   = outputs.NoOutput;
            Builder <object> builder = new Builder <object>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, shareMaxTailLength, outputs, null, false, PackedInt32s.DEFAULT, true, 15);

            BytesRef          scratch = new BytesRef();
            BytesRef          entry;
            Int32sRef         scratchIntsRef = new Int32sRef();
            int               count          = 0;
            IBytesRefIterator iter           = sorter.GetIterator();

            while ((entry = iter.Next()) != null)
            {
                count++;
                if (scratch.CompareTo(entry) != 0)
                {
                    builder.Add(Util.Fst.Util.ToInt32sRef(entry, scratchIntsRef), empty);
                    scratch.CopyBytes(entry);
                }
            }

            return(count == 0 ? null : builder.Finish());
        }
Ejemplo n.º 4
0
        public void TestFieldContents_2()
        {
            IBytesRefEnumerator it;

            try
            {
                indexReader = DirectoryReader.Open(store);

                ld = new LuceneDictionary(indexReader, "contents");
                it = ld.GetEntryEnumerator();

                // just iterate through words
                assertTrue(it.MoveNext());
                assertEquals("First element isn't correct", "Jerry", it.Current.Utf8ToString());
                assertTrue(it.MoveNext());
                assertEquals("Second element isn't correct", "Tom", it.Current.Utf8ToString());
                assertFalse("Nonexistent element is really null", it.MoveNext());
            }
            finally
            {
                if (indexReader != null)
                {
                    indexReader.Dispose();
                }
            }
        }
Ejemplo n.º 5
0
        public void TestFieldContents_1()
        {
            try
            {
                indexReader = DirectoryReader.Open(store);

                ld = new LuceneDictionary(indexReader, "contents");
                it = ld.GetEntryIterator();

                assertNotNull("First element doesn't exist.", spare = it.Next());
                assertTrue("First element isn't correct", spare.Utf8ToString().equals("Jerry"));
                assertNotNull("Second element doesn't exist.", spare = it.Next());
                assertTrue("Second element isn't correct", spare.Utf8ToString().equals("Tom"));
                assertNull("More elements than expected", it.Next());

                ld = new LuceneDictionary(indexReader, "contents");
                it = ld.GetEntryIterator();

                int counter = 2;
                while (it.Next() != null)
                {
                    counter--;
                }

                assertTrue("Number of words incorrect", counter == 0);
            }
            finally
            {
                if (indexReader != null)
                {
                    indexReader.Dispose();
                }
            }
        }
        public void TestEmpty()
        {
            Directory   dir    = NewDirectory();
            IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));

            writer.Commit();
            writer.Dispose();
            IndexReader       ir         = DirectoryReader.Open(dir);
            IDictionary       dictionary = new HighFrequencyDictionary(ir, "bogus", 0.1f);
            IBytesRefIterator tf         = dictionary.GetEntryIterator();

            assertNull(tf.Comparer);
            assertNull(tf.Next());
            dir.Dispose();
        }
Ejemplo n.º 7
0
        public virtual void TestAppend()
        {
            Random         random     = Random;
            BytesRefArray  list       = new BytesRefArray(Util.Counter.NewCounter());
            IList <string> stringList = new List <string>();

            for (int j = 0; j < 2; j++)
            {
                if (j > 0 && random.NextBoolean())
                {
                    list.Clear();
                    stringList.Clear();
                }
                int      entries  = AtLeast(500);
                BytesRef spare    = new BytesRef();
                int      initSize = list.Length;
                for (int i = 0; i < entries; i++)
                {
                    string randomRealisticUnicodeString = TestUtil.RandomRealisticUnicodeString(random);
                    spare.CopyChars(randomRealisticUnicodeString);
                    Assert.AreEqual(i + initSize, list.Append(spare));
                    stringList.Add(randomRealisticUnicodeString);
                }
                for (int i = 0; i < entries; i++)
                {
                    Assert.IsNotNull(list.Get(spare, i));
                    Assert.AreEqual(stringList[i], spare.Utf8ToString(), "entry " + i + " doesn't match");
                }

                // check random
                for (int i = 0; i < entries; i++)
                {
                    int e = random.Next(entries);
                    Assert.IsNotNull(list.Get(spare, e));
                    Assert.AreEqual(stringList[e], spare.Utf8ToString(), "entry " + i + " doesn't match");
                }
                for (int i = 0; i < 2; i++)
                {
                    IBytesRefIterator iterator = list.GetIterator();
                    foreach (string @string in stringList)
                    {
                        Assert.AreEqual(@string, iterator.Next().Utf8ToString());
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void TestFieldNonExistent()
        {
            try
            {
                indexReader = DirectoryReader.Open(store);

                ld = new LuceneDictionary(indexReader, "nonexistent_field");
                it = ld.GetEntryIterator();

                assertNull("More elements than expected", spare = it.Next());
            }
            finally
            {
                if (indexReader != null)
                {
                    indexReader.Dispose();
                }
            }
        }
Ejemplo n.º 9
0
        public void TestFieldAaa()
        {
            try
            {
                indexReader = DirectoryReader.Open(store);

                ld = new LuceneDictionary(indexReader, "aaa");
                it = ld.GetEntryIterator();
                assertNotNull("First element doesn't exist.", spare = it.Next());
                assertTrue("First element isn't correct", spare.Utf8ToString().equals("foo"));
                assertNull("More elements than expected", it.Next());
            }
            finally
            {
                if (indexReader != null)
                {
                    indexReader.Dispose();
                }
            }
        }
Ejemplo n.º 10
0
        public virtual void TestSort()
        {
            Random        random     = Random;
            BytesRefArray list       = new BytesRefArray(Util.Counter.NewCounter());
            List <string> stringList = new List <string>();

            for (int j = 0; j < 2; j++)
            {
                if (j > 0 && random.NextBoolean())
                {
                    list.Clear();
                    stringList.Clear();
                }
                int      entries  = AtLeast(500);
                BytesRef spare    = new BytesRef();
                int      initSize = list.Length;
                for (int i = 0; i < entries; i++)
                {
                    string randomRealisticUnicodeString = TestUtil.RandomRealisticUnicodeString(random);
                    spare.CopyChars(randomRealisticUnicodeString);
                    Assert.AreEqual(initSize + i, list.Append(spare));
                    stringList.Add(randomRealisticUnicodeString);
                }

                // LUCENENET NOTE: Must sort using ArrayUtil.GetNaturalComparator<T>()
                // to ensure culture isn't taken into consideration during the sort,
                // which will match the sort order of BytesRef.UTF8SortedAsUTF16Comparer.
                CollectionUtil.TimSort(stringList);
#pragma warning disable 612, 618
                IBytesRefIterator iter = list.GetIterator(BytesRef.UTF8SortedAsUTF16Comparer);
#pragma warning restore 612, 618
                int a = 0;
                while ((spare = iter.Next()) != null)
                {
                    Assert.AreEqual(stringList[a], spare.Utf8ToString(), "entry " + a + " doesn't match");
                    a++;
                }
                Assert.IsNull(iter.Next());
                Assert.AreEqual(a, stringList.Count);
            }
        }
Ejemplo n.º 11
0
        public void TestFieldNonExistent()
        {
            IBytesRefEnumerator it;

            try
            {
                indexReader = DirectoryReader.Open(store);

                ld = new LuceneDictionary(indexReader, "nonexistent_field");
                it = ld.GetEntryEnumerator();

                assertFalse("More elements than expected", it.MoveNext());
            }
            finally
            {
                if (indexReader != null)
                {
                    indexReader.Dispose();
                }
            }
        }
Ejemplo n.º 12
0
        public void TestFieldAaa()
        {
            IBytesRefEnumerator it;

            try
            {
                indexReader = DirectoryReader.Open(store);

                ld = new LuceneDictionary(indexReader, "aaa");
                it = ld.GetEntryEnumerator();
                assertTrue("First element doesn't exist.", it.MoveNext());
                assertTrue("First element isn't correct", it.Current.Utf8ToString().Equals("foo", StringComparison.Ordinal));
                assertFalse("More elements than expected", it.MoveNext());
            }
            finally
            {
                if (indexReader != null)
                {
                    indexReader.Dispose();
                }
            }
        }
Ejemplo n.º 13
0
        public void TestFieldContents_1()
        {
            IBytesRefEnumerator it;

            try
            {
                indexReader = DirectoryReader.Open(store);

                ld = new LuceneDictionary(indexReader, "contents");
                it = ld.GetEntryEnumerator();

                assertTrue("First element doesn't exist.", it.MoveNext());
                assertTrue("First element isn't correct", it.Current.Utf8ToString().Equals("Jerry", StringComparison.Ordinal));
                assertTrue("Second element doesn't exist.", it.MoveNext());
                assertTrue("Second element isn't correct", it.Current.Utf8ToString().Equals("Tom", StringComparison.Ordinal));
                assertFalse("More elements than expected", it.MoveNext());

                ld = new LuceneDictionary(indexReader, "contents");
                it = ld.GetEntryEnumerator();

                int counter = 2;
                while (it.MoveNext())
                {
                    counter--;
                }

                assertTrue("Number of words incorrect", counter == 0);
            }
            finally
            {
                if (indexReader != null)
                {
                    indexReader.Dispose();
                }
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Creates a new wrapper, wrapping the specified iterator and
 /// specifying a weight value of <c>1</c> for all terms
 /// and nullifies associated payloads.
 /// </summary>
 public InputIteratorWrapper(IBytesRefIterator wrapped)
 {
     this.wrapped = wrapped;
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Creates a new wrapper, wrapping the specified iterator and
 /// specifying a weight value of <code>1</code> for all terms.
 /// </summary>
 public TermFreqIteratorWrapper(IBytesRefIterator wrapped)
 {
     this.wrapped = wrapped;
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Indexes the data from the given <see cref="IDictionary"/>. </summary>
        /// <param name="dict"> Dictionary to index </param>
        /// <param name="config"> <see cref="IndexWriterConfig"/> to use </param>
        /// <param name="fullMerge"> whether or not the spellcheck index should be fully merged </param>
        /// <exception cref="ObjectDisposedException"> if the <see cref="SpellChecker"/> is already disposed </exception>
        /// <exception cref="System.IO.IOException"> If there is a low-level I/O error. </exception>
        public void IndexDictionary(IDictionary dict, IndexWriterConfig config, bool fullMerge)
        {
            lock (modifyCurrentIndexLock)
            {
                EnsureOpen();
                Directory dir = this.spellIndex;
                using (var writer = new IndexWriter(dir, config))
                {
                    IndexSearcher     indexSearcher = ObtainSearcher();
                    IList <TermsEnum> termsEnums    = new List <TermsEnum>();

                    IndexReader reader = searcher.IndexReader;
                    if (reader.MaxDoc > 0)
                    {
                        foreach (AtomicReaderContext ctx in reader.Leaves)
                        {
                            Terms terms = ctx.AtomicReader.GetTerms(F_WORD);
                            if (terms != null)
                            {
                                termsEnums.Add(terms.GetIterator(null));
                            }
                        }
                    }

                    bool isEmpty = termsEnums.Count == 0;

                    try
                    {
                        IBytesRefIterator iter = dict.GetEntryIterator();
                        BytesRef          currentTerm;

                        while ((currentTerm = iter.Next()) != null)
                        {
                            string word = currentTerm.Utf8ToString();
                            int    len  = word.Length;
                            if (len < 3)
                            {
                                continue; // too short we bail but "too long" is fine...
                            }

                            if (!isEmpty)
                            {
                                foreach (TermsEnum te in termsEnums)
                                {
                                    if (te.SeekExact(currentTerm))
                                    {
                                        goto termsContinue;
                                    }
                                }
                            }

                            // ok index the word
                            var doc = CreateDocument(word, GetMin(len), GetMax(len));
                            writer.AddDocument(doc);
termsContinue:
                            ;
                        }
                    }
                    finally
                    {
                        ReleaseSearcher(indexSearcher);
                    }
                    if (fullMerge)
                    {
                        writer.ForceMerge(1);
                    }
                }
                // TODO: this isn't that great, maybe in the future SpellChecker should take
                // IWC in its ctor / keep its writer open?

                // also re-open the spell index to see our own changes when the next suggestion
                // is fetched:
                SwapSearcher(dir);
            }
        }