public bool Contains(ObjectVariants subject, ObjectVariants predicate, ObjectVariants obj) { int ssubj = (((OV_iriint)subject)).code; int pred = (((OV_iriint)predicate)).code; var objVar = (((ObjectVariants)obj)); var key_triple = new SPO_Troyka(ssubj, pred, objVar); IEnumerable <PaEntry> entities = spo_ind.GetAllByKey(key_triple); return(entities.Any()); }
//public void BuildIndexes() //{ // table.BuildIndexes(); //} public IEnumerable <object> GetAllByKey(int column, object key) { int i; for (i = 0; i < cnoms.Length; i++) { if (cnoms[i] == column) { break; } } if (i == cnoms.Length) { throw new Exception("Err: 938948"); } var index = allindexes[i]; if (index is IndexDynamic <int, IndexKeyImmutable <int> > ) { IndexDynamic <int, IndexKeyImmutable <int> > ind = (IndexDynamic <int, IndexKeyImmutable <int> >)index; return(ind.GetAllByKey((int)key).Select(ent => ((object[])ent.Get())[1])); } else if (index is IndexDynamic <string, IndexHalfkeyImmutable <string> > ) { IndexDynamic <string, IndexHalfkeyImmutable <string> > ind = (IndexDynamic <string, IndexHalfkeyImmutable <string> >)index; return(ind.GetAllByKey((string)key).Select(ent => ((object[])ent.Get())[1])); } return(null); }
protected virtual IEnumerable <int> GetParentsByCode(int code) { while ((code = code / maxChildrenCount) > 0) { yield return((int)decodingIndex.GetAllByKey(code).First().Get()); } }
public virtual bool TestConnection(int node1, int node2) { var codes1 = codingIndex.GetAllByKey(node1).ToArray(); if (!codes1.Any()) { return(false); } var codes2 = codingIndex.GetAllByKey(node2).ToArray(); if (!codes2.Any()) { return(false); } return(TestConnectionByCodes((int)codes1[0].Get(), (int)codes2[0].Get())); }
public IEnumerable <T> GetTriplesWithSubject <T>(ObjectVariants s, Func <ObjectVariants, ObjectVariants, T> returns) { return(s_ind.GetAllByKey(((OV_iriint)s).code) .Select(entry => entry.Get()) .Cast <object[]>() .Select(row => returns(ReadPredicate(((object[])row[1])), ReadSubject(((object[])row[1]))))); }
public object[] GetPersonByCode(int code) { var ob = index_person.GetAllByKey(code) .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); return((object[])ob); }
public IEnumerable <ObjectVariants> GetTriplesWithSubjectPredicate(ObjectVariants subject, ObjectVariants predicate) { IEnumerable <PaEntry> entities = sp_ind.GetAllByKey(new SP_Pair(((OV_iriint)subject).code, ((OV_iriint)predicate).code)); return(entities .Select(entry => entry.Get()) .Cast <object[]>() .Select(row => ((object[])row[1])[2].ToOVariant(ng.coding_table.GetStringByCode))); }
public string GetNameByCode(int code) { var ob = index_person.GetAllByKey(code) .Select(ent => ((object[])ent.Get())[1]) .Cast <object[]>() .FirstOrDefault(); return((string)ob[1]); }
public IEnumerable <ObjectVariants> GetTriplesWithPredicateObject(ObjectVariants predicate, ObjectVariants obj) { int pred = (((OV_iriint)predicate)).code; var objVar = (((ObjectVariants)obj)); var key_triple = new PO_Pair(pred, objVar); IEnumerable <PaEntry> entities = po_ind.GetAllByKey(key_triple); return(entities .Select(entry => entry.Get()) .Cast <object[]>() .Select(row => ng.GetCoded((int)((object[])row[1])[0]))); }
public IEnumerable <ObjectVariants> GetTriplesWithSubjectObject(ObjectVariants subject, ObjectVariants obj) { int ssubj = (((OV_iriint)subject)).code; var objVar = (((ObjectVariants)obj)); var key_triple = new PO_Pair(ssubj, objVar); IEnumerable <PaEntry> entities = so_ind.GetAllByKey(key_triple); return(entities .Select(entry => entry.Get()) .Cast <object[]>() .Select(row => ng.GetCoded((int)((object[])row[1])[1]))); }
public int GetPersonsByName(string name) { PaEntry entry = tab_person.Element(0); int code = index_person_name.GetAllByKey(name) .Select(ent => { object[] obs = (object[])ent.Get(); return(obs); }) .Where(obs => !(bool)obs[0]) .Select(obs => (int)((object[])obs[1])[0]) .FirstOrDefault(); if (code.ToString() != name) { Console.WriteLine("code={0} name={1}", code, name); } return(code); }
//static string path = "Databases/"; public static void Main4() { Random rnd = new Random(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); Console.WriteLine("Start demo of table and Universal Index with PagedStorage"); // Тип основной таблицы PType tp_person = new PTypeRecord( new NamedType("id", new PType(PTypeEnumeration.integer)), new NamedType("name", new PType(PTypeEnumeration.sstring)), new NamedType("age", new PType(PTypeEnumeration.real))); // ======================== Теперь нам понадобится страничное хранилище ========================= // файл - носитель хранилища string filepath = dbpath + "storage.bin"; bool fob_exists = File.Exists(filepath); // этот признак используется при разных процессах инициализации // Открываем иили создаем файл-носитель хранилища FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite); // Создаем собственно блочное (страничное) хранилище FileOfBlocks fob = new FileOfBlocks(fs); // Далее идет корявый способ создания трех потоков (Stream), нужных для базы данных Stream first_stream = fob.GetFirstAsStream(); if (!fob_exists) { PagedStream.InitPagedStreamHead(first_stream, 8L, 0, PagedStream.HEAD_SIZE); fob.Flush(); } PagedStream main_stream = new PagedStream(fob, fob.GetFirstAsStream(), 8L); long sz = PagedStream.HEAD_SIZE; // Если main_stream нулевой длины, надо инициировать конфигурацию стримов if (main_stream.Length == 0) { // инициируем 3 головы для потоков PagedStream.InitPagedStreamHead(main_stream, 0L, 0L, -1L); PagedStream.InitPagedStreamHead(main_stream, sz, 0L, -1L); PagedStream.InitPagedStreamHead(main_stream, 2 * sz, 0L, -1L); main_stream.Flush(); fob.Flush(); } // создадим 3 потока PagedStream stream_person = new PagedStream(fob, main_stream, 0L); PagedStream stream_index = new PagedStream(fob, main_stream, 1 * sz); PagedStream stream_scale = new PagedStream(fob, main_stream, 2 * sz); // =========================== OK ========================== // База данных такая же, как и в программе 3, только вместо файлов используются потоки TableView tab_person = new TableView(stream_person, tp_person); Func <object, int> person_code_keyproducer = v => (int)((object[])((object[])v)[1])[0]; IndexKeyImmutable <int> ind_arr_person = new IndexKeyImmutable <int>(stream_index) { Table = tab_person, KeyProducer = person_code_keyproducer, Scale = null }; ind_arr_person.Scale = new ScaleCell(stream_scale) { IndexCell = ind_arr_person.IndexCell }; IndexDynamic <int, IndexKeyImmutable <int> > index_person = new IndexDynamic <int, IndexKeyImmutable <int> >(true) { Table = tab_person, IndexArray = ind_arr_person, KeyProducer = person_code_keyproducer }; tab_person.RegisterIndex(index_person); fob.DeactivateCache(); int nelements = 1000000; bool toload = true; // Загружать или нет новую базу данных if (toload) { sw.Restart(); // Очистим ячейки последовательности и индекса tab_person.Clear(); IEnumerable <object> flow = Enumerable.Range(0, nelements) .Select(i => { int id = nelements - i; string name = "=" + id.ToString() + "="; double age = rnd.NextDouble() * 100.0; return(new object[] { id, name, age }); }); tab_person.Fill(flow); // Теперь надо отсортировать индексный массив по ключу tab_person.BuildIndexes(); sw.Stop(); Console.WriteLine("Load ok. duration for {0} elements: {1} ms", nelements, sw.ElapsedMilliseconds); } sw.Restart(); // Загрузка кеша ускоряет обработку fob.LoadCache(); sw.Stop(); Console.WriteLine("Cache load duration={0}", sw.ElapsedMilliseconds); // Проверим работу int search_key = nelements * 2 / 3; var ob = index_person.GetAllByKey(search_key) .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); if (ob == null) { throw new Exception("Didn't find person " + search_key); } Console.WriteLine("Person {0} has name {1}", search_key, ((object[])ob)[1]); // Засечем скорость выборок int nte = 10000; sw.Restart(); for (int i = 0; i < nte; i++) { search_key = rnd.Next(nelements) + 1; ob = index_person.GetAllByKey(search_key) .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); if (ob == null) { throw new Exception("Didn't find person " + search_key); } string nam = (string)((object[])ob)[1]; } sw.Stop(); Console.WriteLine("Duration for {2} search in {0} elements: {1} ms", nelements, sw.ElapsedMilliseconds, nte); }
public static void Main4(string[] args) { Random rnd = new Random(); Console.WriteLine("Start Task04_Sequenses_Main3"); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); PType tp_person = new PTypeRecord( new NamedType("id", new PType(PTypeEnumeration.integer)), new NamedType("name", new PType(PTypeEnumeration.sstring)), new NamedType("age", new PType(PTypeEnumeration.real))); TableView tab_person = new TableView(path + "tab_person.pac", tp_person); IndexViewImmutable <string> name_index = new IndexViewImmutable <string>(path + "name_index.pac") { Table = tab_person, KeyProducer = v => (string)((object[])((object[])v)[1])[1] }; IndexDynamic <string, IndexViewImmutable <string> > index_person_name = new IndexDynamic <string, IndexViewImmutable <string> >(false, name_index); tab_person.RegisterIndex(index_person_name); int nelements = 1_000_000; bool toload = true; // Загружать или нет новую базу данных if (toload) { sw.Restart(); // Очистим ячейки последовательности и индекса tab_person.Clear(); IEnumerable <object> flow = Enumerable.Range(0, nelements) .Select(i => { int id = nelements - i; string name = "=" + id.ToString() + "="; double age = rnd.NextDouble() * 100.0; return(new object[] { id, name, age }); }); tab_person.Fill(flow); // Теперь надо отсортировать индексный массив по ключу tab_person.BuildIndexes(); sw.Stop(); Console.WriteLine("Load ok. duration for {0} elements: {1} ms", nelements, sw.ElapsedMilliseconds); } else { tab_person.Warmup(); } // Проверим работу int search_key = nelements * 2 / 3; var ob = index_person_name.GetAllByKey("=" + search_key + "=") .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); if (ob == null) { throw new Exception("Didn't find person " + search_key); } Console.WriteLine("Person {0} has name {1}", search_key, ((object[])ob)[1]); // Засечем скорость выборок int nprobe = 1000; sw.Restart(); for (int i = 0; i < nprobe; i++) { search_key = rnd.Next(nelements) + 1; ob = index_person_name.GetAllByKey("=" + search_key + "=") .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); if (ob == null) { throw new Exception("Didn't find person " + search_key); } string nam = (string)((object[])ob)[1]; } sw.Stop(); Console.WriteLine($"Duration for {nprobe} search in {nelements} elements: {sw.ElapsedMilliseconds} ms"); string search_string = "=66666"; var query = index_person_name.GetAllByLevel((PaEntry entry) => { var name = (string)((object[])((object[])entry.Get())[1])[1]; if (name.StartsWith(search_string)) { return(0); } return(name.CompareTo(search_string)); }); foreach (object v in query.Select(entry => ((object[])entry.Get())[1])) { Console.WriteLine(tp_person.Interpret(v)); } }
public static void Main3(string[] args) { Random rnd = new Random(); Console.WriteLine("Start Task04_Sequenses_Main2"); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); PType tp_person = new PTypeRecord( new NamedType("id", new PType(PTypeEnumeration.integer)), new NamedType("name", new PType(PTypeEnumeration.sstring)), new NamedType("rage", new PType(PTypeEnumeration.real))); TableView tab_person = new TableView(path + "tab_person.pac", tp_person); Func <object, int> person_code_keyproducer = v => (int)((object[])((object[])v)[1])[0]; IndexKeyImmutable <int> ind_arr_person = new IndexKeyImmutable <int>(path + "person_ind") { Table = tab_person, KeyProducer = person_code_keyproducer, Scale = null }; //ind_arr_person.Scale = new ScaleCell(path + "person_ind") { IndexCell = ind_arr_person.IndexCell }; IndexDynamic <int, IndexKeyImmutable <int> > index_person = new IndexDynamic <int, IndexKeyImmutable <int> >(true, ind_arr_person); tab_person.RegisterIndex(index_person); int nelements = 1_000_000; bool toload = true; // Загружать или нет новую базу данных if (toload) { sw.Restart(); // Очистим ячейки последовательности и индекса tab_person.Clear(); IEnumerable <object> flow = Enumerable.Range(0, nelements) .Select(i => { int id = nelements - i; string name = "=" + id.ToString() + "="; double age = rnd.NextDouble() * 100.0; return(new object[] { id, name, age }); }); tab_person.Fill(flow); // Теперь надо отсортировать индексный массив по ключу tab_person.BuildIndexes(); sw.Stop(); Console.WriteLine("Load ok. duration for {0} elements: {1} ms", nelements, sw.ElapsedMilliseconds); } else { tab_person.Warmup(); } // Проверим работу int search_key = nelements * 2 / 3; var ob = index_person.GetAllByKey(search_key) .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); if (ob == null) { throw new Exception("Didn't find person " + search_key); } Console.WriteLine("Person {0} has name {1}", search_key, ((object[])ob)[1]); // Засечем скорость выборок int nprobe = 1000; sw.Restart(); for (int i = 0; i < nprobe; i++) { search_key = rnd.Next(nelements) + 1; ob = index_person.GetAllByKey(search_key) .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); if (ob == null) { throw new Exception("Didn't find person " + search_key); } string nam = (string)((object[])ob)[1]; } sw.Stop(); Console.WriteLine($"Duration for {nprobe} search in {nelements} elements: {sw.ElapsedMilliseconds} ms"); }
//static string path = "Databases/"; public static void Main6() { Random rnd = new Random(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); Console.WriteLine("Start demo of table and Universal Index with PagedStorage and id as string"); // Тип основной таблицы PType tp_person = new PTypeRecord( new NamedType("id", new PType(PTypeEnumeration.sstring)), new NamedType("name", new PType(PTypeEnumeration.sstring)), new NamedType("age", new PType(PTypeEnumeration.real))); // ======================== Страничное хранилище возьмем из описания PagedStreamStore ========================= //PagedStreamStore ps_store = new PagedStreamStore(path + "storage.bin", 4); // заказали 4 стрима, конкретные будут: ps_store[i] StreamStorage ps_store = new StreamStorage(dbpath + "storage6uindex.bin", 4); // База данных такая же, как и в программе 4, только идентификатор определен как строка, придется воспользоваться полуключем TableView tab_person; IndexHalfkeyImmutable <string> index_id_arr; IndexDynamic <string, IndexHalfkeyImmutable <string> > index_id; // Подключение к таблице tab_person = new TableView(ps_store[0], tp_person); // Подключение к индексу по уникальному идентификатору (нулевое поле) Func <object, string> person_id_keyproducer = v => (string)((object[])((object[])v)[1])[0]; index_id_arr = new IndexHalfkeyImmutable <string>(ps_store[1]) { Table = tab_person, KeyProducer = person_id_keyproducer, HalfProducer = s => Hashfunctions.HashRot13(s), Scale = null }; index_id_arr.Scale = new ScaleCell(ps_store[2]) { IndexCell = index_id_arr.IndexCell }; index_id = new IndexDynamic <string, IndexHalfkeyImmutable <string> >(true) { Table = tab_person, IndexArray = index_id_arr, KeyProducer = person_id_keyproducer }; tab_person.RegisterIndex(index_id); int nelements = 1000000; bool toload = false; // Загружать или нет новую базу данных if (toload) { sw.Restart(); // Очистим ячейки последовательности и индекса tab_person.Clear(); IEnumerable <object> flow = Enumerable.Range(0, nelements) .Select(i => { int id = nelements - i; string name = "=" + id.ToString() + "="; double age = rnd.NextDouble() * 100.0; return(new object[] { id.ToString(), name, age }); }); tab_person.Fill(flow); // Теперь надо отсортировать индексный массив по ключу tab_person.BuildIndexes(); sw.Stop(); Console.WriteLine("Load ok. duration for {0} elements: {1} ms", nelements, sw.ElapsedMilliseconds); } else { // Загрузка кеша ускоряет обработку sw.Restart(); ps_store.LoadCache(); sw.Stop(); Console.WriteLine("Cache load duration={0}", sw.ElapsedMilliseconds); } // Проверим работу int search_key = nelements * 2 / 3; var ob = index_id.GetAllByKey(search_key.ToString()) .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); if (ob == null) { throw new Exception("Didn't find person " + search_key); } Console.WriteLine("Person {0} has name {1}", search_key, ((object[])ob)[1]); // Засечем скорость выборок int nprobes = 10000; sw.Restart(); for (int i = 0; i < nprobes; i++) { search_key = rnd.Next(nelements) + 1; ob = index_id.GetAllByKey(search_key.ToString()) .Select(ent => ((object[])ent.Get())[1]) .FirstOrDefault(); if (ob == null) { throw new Exception("Didn't find person " + search_key); } string nam = (string)((object[])ob)[1]; } sw.Stop(); Console.WriteLine("Duration for {0} search in {1} elements: {2} ms", nprobes, nelements, sw.ElapsedMilliseconds); }
public static void Main7() { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); string path = "../../../Databases/"; int NumberOfRecords = 100000000; Random rnd = new Random(); Console.WriteLine("Start Universal Index. Main7()"); PType tp_table_element = new PTypeRecord( new NamedType("name", new PType(PTypeEnumeration.sstring)), new NamedType("age", new PType(PTypeEnumeration.integer))); TableView table = new TableView(path + "table", tp_table_element); sw.Restart(); bool tobuild = false; if (tobuild) { table.Fill(Enumerable.Range(0, NumberOfRecords).Select(i => (object)(new object[] { i.ToString(), i == NumberOfRecords / 2 ? -1 : i }))); sw.Stop(); Console.WriteLine("Load Table of {0} elements ok. Duration {1}", NumberOfRecords, sw.ElapsedMilliseconds); } else table.Warmup(); sw.Restart(); // Делаем индекс var ha = new IndexHalfkeyImmutable<string>(path + "dyna_index_str_half") { Table = table, KeyProducer = va => (string)((object[])(((object[])va)[1]))[0], HalfProducer = k => k.GetHashCode() }; ha.Scale = new ScaleCell(path + "dyna_index_str_half") { IndexCell = ha.IndexCell }; bool tobuild_h_index = false; if (tobuild_h_index) { ha.Build(); } else { ha.Warmup(); //ha.BuildScale(); } IndexDynamic<string, IndexHalfkeyImmutable<string>> h_index = new IndexDynamic<string, IndexHalfkeyImmutable<string>>(true) { Table = table, KeyProducer = va => (string)((object[])(((object[])va)[1]))[0], IndexArray = ha }; Console.WriteLine("h_index Build ok. Duration {0}", sw.ElapsedMilliseconds); sw.Restart(); int cnt = 0; for (int i = 0; i < 1000; i++) { int c = h_index.GetAllByKey(rnd.Next(NumberOfRecords * 3 / 2 - 1).ToString()).Count(); if (c > 1) Console.WriteLine("Unexpected Error: {0}", c); cnt += c; } sw.Stop(); Console.WriteLine("1000 GetAllByKey ok. Duration={0} cnt={1}", sw.ElapsedMilliseconds, cnt); }