public static void GenerateTripletFlowNt2(string fileName, long limit, sema2012m.Engine engine, sema2012m.LogLine turlog) { StreamReader sr = new StreamReader(fileName); // Начало транзакции ввода engine.InitAdapterBuffers(); //engine.IncludeXElement(xelement); XElement xelement = null; string current_subject = null; long cnt = 0; string line = null; bool skip = false; while ((line = sr.ReadLine()) != null) { if (cnt > limit) break; cnt++; if (cnt % 1000000 == 0) turlog("Загружено: " + cnt + " линий."); if (string.IsNullOrWhiteSpace(line) || line[0] == '@') continue; string subject; int position = GetEntityOrLiteral(line, 0, out subject); if (subject == null) continue; string predicate; position = GetEntityOrLiteral(line, position, out predicate); if (predicate == null) continue; string obj; bool isObjectProperty = line[position] == '\"' ? false : true; position = GetEntityOrLiteral(line, position, out obj); if (obj == null) continue; if (xelement == null || subject != current_subject) { if (!skip && xelement != null) engine.IncludeXElement(xelement); xelement = new XElement(sema2012m.ONames.rdfdescription, new XAttribute(sema2012m.ONames.rdfabout, subject)); current_subject = subject; } if (xelement.Elements().Count() > 100) continue; if (isObjectProperty) { xelement.Add(new XElement(sema2012m.ONames.GetXName(predicate), new XAttribute(sema2012m.ONames.rdfresource, obj))); } else // DatatypeProperty { xelement.Add(new XElement(sema2012m.ONames.GetXName(predicate), obj)); // пока без языкового спецификатора } } if (!skip && xelement != null) engine.IncludeXElement(xelement); // Конец транзакции ввода engine.FlushAdapterBuffers(); }
protected override void AddTripletToBuffer(sema2012m.Triplet triplet) { string line; if (triplet is DProp) { DProp dp = triplet as DProp; line = "<" + dp.s + ">\t<" + dp.p + ">\t\"" + dp.d.Replace('"', '\'') + "\"" + (dp.lang == null ? "" : "@" + dp.lang) + "."; } else // OProp { OProp op = triplet as OProp; line = "<" + op.s + ">\t<" + op.p + ">\t<" + op.o + ">."; } datawriter.WriteLine(line); }
public override void StartFillDb(sema2012m.LogLine Protocol) { datawriter = new StreamWriter(connection.Path + "data.bin", false, System.Text.Encoding.UTF8); }
public override void FinishFillDb(sema2012m.LogLine Protocol) { datawriter.Close(); CreateDatabase(); }
public static void LoadFromCassettesExpress(sema2012m.LogLine Protocol, sema2012m.LogLine DbConvertErrors) { engine.LoadFromCassettesExpress(CassetteKernel.CassettesConnection.GetFogFiles().Select(x => x.filePath).ToArray(), Protocol, DbConvertErrors); }
public override void StartFillDb(sema2012m.LogLine Protocol) { if (connection.State == System.Data.ConnectionState.Open) connection.Close(); connection.Open(); // Этот оператор может выдавать Exception. Напр. из-за отсутствия файла БД, но без открытия, ничего не получится try { string[] commands1 = new string[] { "DROP TABLE rdf_entities;", "DROP TABLE rdf_literals;", "DROP TABLE rdf_ostatements;", "DROP TABLE rdf_dstatements;"}; string sql1 = commands1.Where(c => c != "").Aggregate((sum, s) => sum + s); DbCommand sqlcommand = connection.CreateCommand(); sqlcommand.CommandText = commands1.Aggregate((sum, s) => sum + s); sqlcommand.ExecuteNonQuery(); } catch (Exception ex) { Protocol("Problem to DROP: " + ex.Message); } try { string[] commands2 = new string[] { "CREATE TABLE rdf_entities (entityid INT NOT NULL, entityvalue NVARCHAR(400) NOT NULL, PRIMARY KEY(entityid));", "CREATE TABlE rdf_literals (literalid INT NOT NULL, literalvalue NVARCHAR(MAX) NOT NULL, literallang NVARCHAR(8), PRIMARY KEY(literalid));", "CREATE TABLE rdf_ostatements (osubject INT NOT NULL, opredicate INT NOT NULL, oobj INT NOT NULL);", "CREATE TABLE rdf_dstatements (dsubject INT NOT NULL, dpredicate INT NOT NULL, data INT NOT NULL);", }; DbCommand sqlcommand = connection.CreateCommand(); sqlcommand.CommandText = commands2.Where(c => c != "").Aggregate((sum, s) => sum + s); sqlcommand.ExecuteNonQuery(); } catch (Exception ex) { Protocol("Err in StartFillDb(): " + ex.Message); } try { string[] commands3 = new string[] { "CREATE INDEX entities_value_index ON rdf_entities(entityvalue);", "CREATE INDEX osubject_index ON rdf_ostatements(osubject);", "CREATE INDEX oobj_index ON rdf_ostatements(oobj);", "CREATE INDEX dsubject_index ON rdf_dstatements(dsubject);", "CREATE INDEX data_index ON rdf_dstatements(data);", //"CREATE INDEX literal_index ON rdf_literals(literalvalue);", }; DbCommand sqlcommand = connection.CreateCommand(); sqlcommand.CommandText = commands3.Where(c => c != "").Aggregate((sum, s) => sum + s); sqlcommand.ExecuteNonQuery(); } catch (Exception ex) { Protocol("Problem to CREATE INDEX: " + ex.Message); } //connection.Close(); // Закрытие будет по FinishFillDb // Установление готовности к приему данных ENT_INDEX = 0; LIT_INDEX = 0; iENTS = new Dictionary<string, int>(); iLITS = new Dictionary<string, int>(); connection.Close(); }
public override void FinishFillDb(sema2012m.LogLine Protocol) { if (connection.State == System.Data.ConnectionState.Open) connection.Close(); }
public override void StartFillDb(sema2012m.LogLine Protocol) { this.Protocol = Protocol; if (connection.State == System.Data.ConnectionState.Open) connection.Close(); connection.Open(); try { var command = connection.CreateCommand(); command.CommandText = "SPARQL CLEAR GRAPH <" + graph + ">"; command.ExecuteNonQuery(); } catch (Exception ex) { Protocol("Problem to DROP graph: " + ex.Message); } connection.Close(); }
public static void GenerateTripletFlowTsv(string fileName, long limit, sema2012m.Engine engine, sema2012m.LogLine turlog) { engine.InitAdapterBuffers(); StreamReader sr = new StreamReader(fileName); Ntriplets = 0; string line; while ((line=sr.ReadLine()) != null) { if (Ntriplets > limit) break; if (Ntriplets % 200000 == 0) turlog("Загружено: " + Ntriplets + " триплетов."); string[] parts = line.Split('\t'); if (parts == null || parts.Length < 4) { continue; } string subj_ = parts[1]; string pred_ = parts[2]; string obj_ = parts[3]; string subj = ConvertEntityId(subj_.Substring(1, subj_.Length - 2)); string pred = pred_[0] == '<' ? pred_.Substring(1, pred_.Length - 2) : pred_; // Надо бы преобразовать конструкции вида rdfs:label в нормальную форму... // Смотрим на объект и определяем вид утверждения char c = obj_[0]; if (c == '<') // объектное свойство { Ntriplets++; //yield return new sema2012m.OProp(subj, pred, obj_.Substring(1, obj_.Length - 2).Replace('\'', '_')); engine.AddTripletToBuffer(new sema2012m.OProp(subj, pred, ConvertEntityId(obj_.Substring(1, obj_.Length - 2)))); } else if (c == '\"') // данные { int pos = obj_.LastIndexOf('\"'); string lang = null; if (pos < obj_.Length - 3 && obj_[pos + 1] == '@') { lang = obj_.Substring(pos + 2); } var dp = new sema2012m.DProp(subj, pred, obj_.Substring(1, pos - 1)); if (lang != null) dp.lang = lang; Ntriplets++; //yield return dp; engine.AddTripletToBuffer(dp); } else // неизвестно что { } } engine.FlushAdapterBuffers(); }
//protected virtual void FillDatabaseFromTripletFlow(IEnumerable<sema2012m.Triplet> tflow, object runcommand, bool append) { } // append - признак, что транзакция работает на добавление БД protected internal virtual void AddTripletToBuffer(sema2012m.Triplet triplet) { }
public virtual void StartFillDb(sema2012m.LogLine Protocol) { }
public virtual void FinishFillDb(sema2012m.LogLine Protocol) { }
private static EntityInfo GetSingleAndCheck(string id, sema2012m.LogLine errlog, string place) { var en_arr = _records.AsQueryable<EntityInfo>().Where(en => en.MergedIds.Contains(id)).ToArray(); if (en_arr.Length == 1) return en_arr[0]; if (en_arr.Length == 0) { errlog("err in " + place + ": no mrecord with id=" + id); } else if (en_arr.Length > 1) { errlog("err in " + place + ": duplicate (" + en_arr.Length + ") mrecords with id=" + id); } return null; }
public static void CheckXFlow(IEnumerable<XElement> xflow, sema2012m.LogLine errlog) { foreach (XElement el in xflow) { if (el.Name == sema2012m.ONames.TagDelete) { string delete_id = el.Attribute(sema2012m.ONames.AttItem_id).Value; // Поиск записи для delete_id EntityInfo delete_en = GetSingleAndCheck(delete_id, errlog, "delete"); if (delete_en != null) { if (!delete_en.IsRemoved) { // Ошибка errlog("Err in delete: record with id=" + delete_id + " didn't deleted"); } } } else if (el.Name == sema2012m.ONames.TagSubstitute) { // Поиск записей для old_id и new_id string old_id = el.Attribute(sema2012m.ONames.AttOld_id).Value; string new_id = el.Attribute(sema2012m.ONames.AttNew_id).Value; EntityInfo old_en = GetSingleAndCheck(old_id, errlog, "substitute (old_id)"); EntityInfo new_en = GetSingleAndCheck(new_id, errlog, "substitute (new_id)"); if (old_en != null && new_en != null) { // проверка, что это мзаписи одинаковые if (old_en.Id != new_en.Id) errlog("err in substitute: old record (id=" + old_id + ") and new record (id=" + new_id + ") are not the same"); // проверка, что old_id != LastId if (old_id == new_en.LastId) errlog("err in substitute: old_id (id=" + old_id + ") is original"); } } else { // это запись var aboutatt = el.Attribute(sema2012m.ONames.rdfabout); if (aboutatt == null) continue; string id = aboutatt.Value; // Выявляем временную отметку DateTime modificationTime_new = DateTime.MinValue; XAttribute mt = el.Attribute(sema2012m.ONames.AttModificationTime); if (mt != null) DateTime.TryParse(mt.Value, out modificationTime_new); modificationTime_new = modificationTime_new.ToUniversalTime(); EntityInfo existant_en = GetSingleAndCheck(id, errlog, "record"); if (existant_en != null) { // если мзапись есть // Все в порядке, если не последний или временная отметка меньше if (existant_en.LastId != id) { } else if (modificationTime_new < existant_en.TimeStamp) { } else if (modificationTime_new > existant_en.TimeStamp) { // Если больше, то ошибка errlog("err in record: mrecord is original, but its TimeStamp > modificationTime_new. id=" + id + " modificationTime_new=" + modificationTime_new.ToString("s") + " existant_en.TimeStamp=" + existant_en.TimeStamp.ToString("s")); errlog(el.ToString()); } else { // Здесь надо сравнить запись и мзапись } } } } }
public void AppendXflowToRiTable(IEnumerable<XElement> xflow, string ff, sema2012m.LogLine err) { foreach (XElement xelement in xflow) { if (xelement.Name == ONames.TagDelete) { XAttribute att = xelement.Attribute("id"); if (att == null) continue; string id = att.Value; if (id == "") continue; if (table_ri.ContainsKey(id)) { var ri = table_ri[id]; if (!ri.removed) // Если признак уже есть, то действия уже произведены { // проверим, что уничтожается оригинал цепочки if (!(id == ri.id)) { err("Уничтожается не оригинал цепочки. fog=" + ff + " id=" + id); } else ri.removed = true; } } else { table_ri.Add(id, new ResInfo(id) { removed = true }); } } else if (xelement.Name == ONames.TagSubstitute) { XAttribute att_old = xelement.Attribute("old-id"); XAttribute att_new = xelement.Attribute("new-id"); if (att_old == null || att_new == null) continue; string id_old = att_old.Value; string id_new = att_new.Value; if (id_old == "" || id_new == "") continue; // Добудем старый и новый ресурсы ResInfo old_res, new_res; if (!table_ri.TryGetValue(id_old, out old_res)) { old_res = new ResInfo(id_old); table_ri.Add(id_old, old_res); } if (!table_ri.TryGetValue(id_new, out new_res)) { new_res = new ResInfo(id_new); table_ri.Add(id_new, new_res); } // Проверим, что old-id совпадает с оригиналом локальной цепочки if (id_old != old_res.id) { //LogFile.WriteLine("Разветвление на идентификаторе: " + id_old); } // Перенесем тип из старой цепочки в новый ресурс if (new_res.typeid == null) new_res.typeid = old_res.typeid; else { // Проверим, что цепочки одинакового типа if (old_res.typeid != null && old_res.typeid != new_res.typeid) { err("Err: сливаются цепочки разных типов"); } } // добавляем список слитых старых идентификаторов в новый ресурс new_res.merged_ids.AddRange(old_res.merged_ids); // пробегаем по списку старых идентификаторов и перекидываем ссылку на новый ресурс foreach (string oid in old_res.merged_ids) table_ri[oid] = new_res; // перекидываем признак removed из старого ресурса, если он там true. if (old_res.removed) { // Похоже, следующий оператор ошибка. Мы "протягиваем" условие removed //new_res.removed = true; err("Протяжка удаления по цепочке. id=" + id_old); } } else { XAttribute idAtt = xelement.Attribute(ONames.rdfabout); if (idAtt == null) continue; string id = idAtt.Value; if (id == "") continue; // if (table_ri.ContainsKey(id)) { var ri = table_ri[id]; DateTime modificationTime = DateTime.MinValue; XAttribute mt = xelement.Attribute(ONames.AttModificationTime); if (mt != null && DateTime.TryParse(mt.Value, out modificationTime) && modificationTime.ToUniversalTime() > ri.timestamp) { // Установим эту временную отметку ri.timestamp = modificationTime.ToUniversalTime(); } if (xelement.Name != sema2012m.ONames.rdfdescription) // rdf:Description не несет информации о типе записи { if (ri.typeid == null) ri.typeid = xelement.Name.NamespaceName + xelement.Name.LocalName; else { // проверка на одинаковость типов if (xelement.Name.NamespaceName + xelement.Name.LocalName != ri.typeid) { err("Err: тип " + xelement.Name + " для ресурса " + idAtt + " не соответствует ранее определенному типу"); } } } } else { // Это вариант, когда входа еще нет в таблице DateTime modificationTime = DateTime.MinValue; XAttribute mt = xelement.Attribute(ONames.AttModificationTime); if (mt != null) DateTime.TryParse(mt.Value, out modificationTime); var n_resinfo = new ResInfo(id) { removed = false, timestamp = modificationTime.ToUniversalTime() //, typeid = xelement.Name.NamespaceName + xelement.Name.LocalName }; if (xelement.Name != sema2012m.ONames.rdfdescription) n_resinfo.typeid = xelement.Name.NamespaceName + xelement.Name.LocalName; table_ri.Add(id, n_resinfo); } } } }
public override void FinishFillDb(sema2012m.LogLine Protocol) { graph.FinishFillDb(); }
public override void StartFillDb(sema2012m.LogLine Protocol) { graph.StartFillDb(); }
private static void InitLog(out sema2012m.LogLine log, string path, bool timestamp) { log = (string line) => { lock (locker) { try { var saver = new System.IO.StreamWriter(path, true, System.Text.Encoding.UTF8); saver.WriteLine((timestamp? (DateTime.Now.ToString("s") + " ") : "")+ line); saver.Close(); } catch (Exception) { //LogFile.WriteLine("Err in buildlog writing: " + ex.Message); } } }; }