Visualizzazione post con etichetta database. Mostra tutti i post
Visualizzazione post con etichetta database. Mostra tutti i post

mercoledì 12 ottobre 2011

MongoDB - Cluster - Sharding and Replica Set


Questa è una configurazione di prova per eseguire dei test sulle possibilità di Cluster con Treplica Set e e bilanciamento del carico con MongoDB (Sharding), il test viene eseguito su una macchina sola, in realtà ogni server mongo deve essere residente su una macchina separata

  •  creo le cartelle per i vari db


/data/r1
/data/r2
/data/r3

/data/r11
/data/r12
/data/r13

/data/cfg1
/data/cfg2

  • configuro ed eseguo i due blocchi di replica (2 blocchi da 3 server)


./mongod --replSet replica1 --dbpath /data/r1 --port 20001 --rest 
./mongod --replSet replica1 --dbpath /data/r2 --port 20002 --rest
./mongod --replSet replica1 --dbpath /data/r3 --port 20003 --rest

./mongod --replSet replica11 --dbpath /data/r11 --port 20011 --rest 
./mongod --replSet replica11 --dbpath /data/r12 --port 20012 --rest
./mongod --replSet replica11 --dbpath /data/r13 --port 20013 --rest

nota: per ogni server è possibile avere l'esecuzione in background e il logging su file aggiungendo --fork --logpath /mongodb/log/<nome_del_file>.log --logappend 
  • eseguo la configurazione per agganciare i server replica.
./mongo localhost:20001

config = {
"_id" : "replica1",
"members" : [
{
"_id" : 1,
"host" : "localhost:20001"
},
{
"_id" : 2,
"host" : "localhost:20002"
},
{
"_id" : 3,
"host" : "localhost:20003"
}
]
}

rs.initiate(config);

----

./mongo localhost:20011

config = {
"_id" : "replica11",
"members" : [
{
"_id" : 1,
"host" : "localhost:20011"
},
{
"_id" : 2,
"host" : "localhost:20012"
},
{
"_id" : 3,
"host" : "localhost:20013"
}
]
}

rs.initiate(config);

----


è possibile accedere alla parte di info via web (opzione --rest) su http://192.168.0.75:21001/ e http://192.168.0.75:21011/

  •  server cfg

./mongod --configsvr --dbpath /data/cfg1 --port 20050 --rest

da qui l'interfaccia web:

http://192.168.0.75:21050/


./mongod --configsvr --dbpath /data/cfg2 --port 20060 --rest

  • Mongo finali

 due mongod per accedere con i client

 ./mongos --configdb localhost:20060 --port 20100 
 ./mongos --configdb localhost:20050 --port 20101 

  • Configurazione Sharding

Collego al mogos finale (che rappresentano la punta del mio sistema)

./mongo localhost:20100
use admin
db.runCommand( { addshard : "replica1/localhost:20001,localhost:20002,localhost:20003" } );
db.runCommand( { addshard : "replica11/localhost:20011,localhost:20012,localhost:20013" } );
  
db.runCommand( { listshards : 1 } );

 a questo punto lo shard su replica è configurato

Primo test, se mi collego al ./mongo localhost:20100 ed eseguo db.runCommand( { listshards : 1 } ); ottengo le configurazioni uguali quindi le info sono propagate a tutto il cluster

------

- a questo punto il client a cui devo accedere sono localhost:20100 e localhost:20101 che sono due erogazioni che dovrebbero essere gestite automaticamente dal driver della mia app.

- il parametro --rest serve ad abilitare l'interfaccia rest del browser. Ogni server è raggiungibile da ip:<porta+1000> es se il server è su localhost:20003 la sua parte web è su http://localhost:21003
  • Test di propagazione
- Collego con una piccola app in java al mongos 20100.
- Carico su un db qualche milione di riga, il cluster propaga e sparpaglia i db interi creati su un ramo di replica e l'altro (replica1 e replica11).
  •  Shard del singolo db: 
./mongo localhost:20100
use admin
db.runCommand( { enablesharding : "freedb" } );
  • Shard di una collection
eseguo uno shard della collection

db.runCommand( { shardcollection : "freedb.disc" , key : { filename : 1 } } );


Dopo diversi db creati e milioni di righe inserite trovo con un ramo di shard corposo e uno quasi libero con soli con 2 db, questo è il risultato dell' autobalancer che appunto bilancia il carico.

  • Consistenza

Caduta di una macchina di replica:

ecco che mi cade un mongo del ramo  localhost:20002 (2), le repliche tengono senza problemi, 
la macchina si è demolita... (elimino il contenuto della cartella /data/r2).
dall'interfaccia web vedo che il server va in recovery: 
localhost:20002 2 RECOVERING initial sync need a member to be primary or secondary to do our initial sync 0:0
poi 
localhost:20002 2 RECOVERING initial sync cloning db: freedb21
etc.

Caduta di due macchina di replica:
butto giù le macchine localhost:20001 e localhost:20002
lancio la mia app, mentre sta girando la app si blocca (forse messa in attesa da driver), il ramo di replica localhost:20003 sembra bloccato, fermo la app.. nulla da fare.
rifaccio ripartire il server 20001, finalmente il 20003 si elegge primary e la app riprende le sue insert, quindi se cadono due macchine sul ramo è possibile che tutto si blocchi e rappresenta la criticità del cluster.

soluzione: creare un server arbiter che aiuti la elezione del master: 
http://tebros.com/2010/11/mongodb-arbiters-with-only-two-replicas/
http://www.mongodb.org/display/DOCS/Upgrading+to+Replica+Sets#UpgradingtoReplicaSets-AddingAnArbiter

mkdir /data/arb1
./mongod --rest --replSet replica1 --dbpath /data/arb1 --port 20005

poi.. cerco chi è il primary all'interno della replica1 dall'interfaccia web http://192.168.0.73:21001/_replSet è il localhost:20003

mongo localhost:20003
use admin
rs.addArb("localhost:20005");
rs.status();

a questo punto dall'interfaccia web http://192.168.0.73:21001/_replSet il server arbitrario è online.

..... il server localhost:20002 va in errore..... :  RECOVERING error RS102 too stale to catch up

http://www.mongodb.org/display/DOCS/Resyncing+a+Very+Stale+Replica+Set+Member

Elimino tutto il contenuto della cartella del cluster 20002  - rm -rf /data/r2/* rifaccio ripartire il server 20002 e riparte di resync

ok, a questo punto le conf sono le seguenti:

localhost:20001 - PRIMARY
localhost:20002 - SECONDARY
localhost:20003 - SECONDARY
localhost:20005 - ARBITER

proseguo con il test per verificare il funzionamento dell'ARBITER.
interrompo i server 20002 e 20001.
..no nulla da fare il server 20003 non viene eletto PRIMARY.. 
..neanche tentando di forzare il server 20003  a PRIMARY la cosa non funziona. 
...quindi per avere una replica consistente è necessario avere almeno 3 server in replica oppure 2 in replica e 1 con arbiter.

-------------

- elimino il contenuto della cartella /data/r2
- inserisco dei dati nel db

./mongo localhost:20100
mongos> use freedb21
switched to db freedb21
mongos> for(i=0;i<100000;i++) db.pippo.insert({"test":"prova","c":i});
mongos> db.pippo.count();
100001
......
......
mongos> db.pippo.count();
5418885

-- db sharding

 ./mongo localhost:20101
MongoDB shell version: 2.0.0
connecting to: localhost:20101/test
mongos> use admin
switched to db admin
mongos> db.runCommand( { enablesharding : "freedb21" } );
{ "ok" : 1 }

- il ramo /data/r2 non ricrea i vari file, devo fermare e far ripartire il server r2, a questo punto il server si sincronizza con tutti i rami della sua replica.

--------









martedì 4 ottobre 2011

MongoDB query e qualche test con indici

Utilizzando il db precedentemente creato eseguo qualche query per verificare la velocità:

db.freedb.disk.find({"artist":"Porcupine Tree"}).skip(0).limit(0)

324 risultati
92,81 secondi

Eseguo nuovamente la query precedente ed ottengo gli stessi tempi, quindi non si è creato una cache per la query.

Eseguo la stessa operazione dal codice java:



package freedbtoMongoDb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

public class Queries {

    static String host = "mongodb1";
    static int port = 27017;
    static String db_name = "freedb";

    public static void main(String[] args) {

        try {

            Mongo m = new Mongo(host, port);

            DB db = m.getDB(db_name);
            DBCollection coll = db.getCollection("disk");

            BasicDBObject query = new BasicDBObject();
            long t1 = System.currentTimeMillis();
            query.put("artist", "Porcupine Tree");


            DBCursor cur = coll.find(query).limit(0).skip(0);
            long t2 = System.currentTimeMillis();
            System.out.println("Tot time Find: " + (t2 - t1));

            while (cur.hasNext()) {
                System.out.println(cur.next());
            }
            long t3 = System.currentTimeMillis();
            System.out.println("Tot time cursor: " + (t3 - t2));

            m.close();

        } catch (Exception e) {

            System.out.println("Exception :" + e.getMessage());
        }
    }
}


Ottengo i seguenti risultati suddivisi per farte di find e retrive dei dati, da quello che si nota la lentezza è nel periodo di retrive dei dati.





Tot time Find: 2
{ "_id" : { "$oid" : "4e846f2330042d8d3130aad3"} , "id" : "blues_480f5d06" , "filename" : "blues/480f5d06" , "revision" : "7" , "title" : "The Sky Moves Sideways" , "genre" : "Rock" , "artist" : "Porcupine Tree" , "length" : "3935" , "year" : "1995" , "extd" : "YEAR: 1995 ID3G: 17" , "tracks" : { "3" : { "title" : "Prepare Yourself"} , "2" : { "title" : "The Moon Touches Your Shoulder"} , "1" : { "title" : "Dislocated Day"} , "0" : { "title" : "The Sky Moves Sideways (phase one)"} , "5" : { "title" : "The Sky Moves Sideways (phase two)"} , "4" : { "title" : "Moonloop"}}}}
etc..
etc..

Tot time cursor: 61270 (1 minuto abbondante)
BUILD SUCCESSFUL (total time: 1 minute 2 seconds)

adesso provo a restringere la query su determinati campi, ad esempio sul nome dell'album (field title).

db.freedb.disk.find({"artist":"Porcupine Tree"}, {title:1}).skip(0).limit(0)

con il terminale stesso risultato precedente:


324 risultati
92,81 secondi
con il seguente codice java:


package freedbtoMongoDb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

public class Queries {

    static String host = "mongodb1";
    static int port = 27017;
    static String db_name = "freedb";

    public static void main(String[] args) {

        try {

            Mongo m = new Mongo(host, port);

            DB db = m.getDB(db_name);
            DBCollection coll = db.getCollection("disk");

            BasicDBObject query = new BasicDBObject();


            query.put("artist", "Porcupine Tree");

            BasicDBObject field = new BasicDBObject();
            field.put("title", "1");

            long t1 = System.currentTimeMillis();
            DBCursor cur = coll.find(query, field).limit(0).skip(0);
            long t2 = System.currentTimeMillis();
            System.out.println("Tot time Find: " + (t2 - t1));

            while (cur.hasNext()) {
                System.out.println(cur.next());
            }
            long t3 = System.currentTimeMillis();
            System.out.println("Tot time cursor: " + (t3 - t2));

            m.close();

        } catch (Exception e) {

            System.out.println("Exception :" + e.getMessage());
        }
    }
}





Risultato:

Tot time Find: 1
{ "_id" : { "$oid" : "4e846f2330042d8d3130aad3"} , "title" : "The Sky Moves Sideways"}
{ "_id" : { "$oid" : "4e846f2330042d8d3130add5"} , "title" : "The Sky Moves Sideways"}
{ "_id" : { "$oid" : "4e846f2330042d8d3130bb1a"} , "title" : "The Sky Moves Sideways"}
{ "_id" : { "$oid" : "4e846f5830042d8d3134caaa"} , "title" : "BBC Sessions 1993 & 1995"}
{ "_id" : { "$oid" : "4e846faa30042d8d31379b9d"} , "title" : "XM ReTracked"}
{ "_id" : { "$oid" : "4e846fba30042d8d3138cc14"} , "title" : "Lightbulb Sun"}
etc.
etc.
etc.
Tot time cursor: 73556
BUILD SUCCESSFUL (total time: 1 minute 14 seconds)



Le tempistiche si mantengono molto vicine al precedente test anche con l'estrazione di un singolo campo.

A questo punto creo un indice semplice sul campo artist.

Eseguo nuovamente i test precedenti.

il primo:


console:
db.freedb.disk.find({"artist":"Porcupine Tree"}).skip(0).limit(0)

324 risultati tempo 0,01 s

in java:


Tot time cursor: 557

il secondo:


console:
db.freedb.disk.find({"artist":"Porcupine Tree"}, {title:1}).skip(0).limit(0)



324 risultati tempo 0,00 s

in java:

Tot time cursor: 63

diciamo che gli indici aiutano parecchio....



[sorgenti in NetBeans]



giovedì 29 settembre 2011

FreeDB to MongoDB


Ultimamente mi trovo a lavorare con MongoDB, ed ecco subito un test di import di massa scritto in java per testare le tempistiche di import e Query del db.

Come al solito utilizzo il freedb, trasformo tutti il db in un succoso file json da 800MB con la classe FreeDbToJson (progetto completo linkato al fondo del post).

questa è una riga del json:

{
   "id":"soundtrack_fe13d011",
   "filename":"soundtrack/fe13d011",
   "revision":"0",
   "title":"100 Love Songs Stage 4 Cd4",
   "genre":"Soundtrack",
   "artist":"IndianDigitalAudio.com",
   "length":"5074",
   "year":"2011",
   "extd":"",
    "tracks":{
              "15":{"title":"Mausam Achanak"},
              "16":{"title":"I Dont Know What To Do"},
              "13":{"title":"Aaja Maahi"},
              "14":{"title":"Janeman"},
              "11":{"title":"Roshan Dil Ka Jahan"},
              "12":{"title":"Yaad Teri Aaye"},
             "3":{"title":"Jo Ghumshuda"},
              "2":{"title":"Dhadke Jiya"},
              "1":{"title":"Nazrein Karam"},
              "10":{"title":"Tum Bhi Ho Wahi"},
             "0":{"title":"Aao Milo Chalo"},
              "7":{"title":"Mausam"},
              "6":{"title":"Mera Pehla Pehla Pyaar"},
              "5":{"title":"Raat Ke Dhai Baje"},
              "4":{"title":"Jaane Tu Meri Kya Hai"},
              "9":{"title":"Pyaar Ki Yeh Kahani"},
              "8":{"title":"Miss You Everyday"}
  }

}
Dopo aver ottenuto questo file eseguo un'altro piccolo programmino in java per importare di massa tutti i record utilizzando la funzionalità requestStart().


package freedbtoMongoDb;

import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.util.JSON;
import java.io.IOException;

public class JsonToMongoDB {

    static String host = "hostname";
    static int port = 27017;
    static String db_name = "freedb";
    static String target_folder = "/marco/mongodb/file/";

    public static void main(String[] args) throws IOException {

        Mongo m = new Mongo(host, port);
        DB db = m.getDB(db_name);
        db.requestStart();

        System.out.println("File: " + target_folder + "disk.json");
       BigFile file = null;
        try {
            file = new BigFile(target_folder + "disk.json");
        } catch (Exception ex) {
            System.out.println("exception: " + ex.getMessage());
        }

        long ts = System.currentTimeMillis();
        int i = 0;
        for (String line : file) {
            db.getCollection("disk").insert((DBObject) JSON.parse(line));
            System.out.println("line: " + i);
            i++;
        }

        System.out.println("tot time: " + (System.currentTimeMillis() - ts));
        db.requestDone();

    }
}

il db mongo server è installato su una vm dedicata invece il programma sopra gira in locale in netbeans, le tempistiche sono state:  - tot time: 959532 ( circa 16 minuti) per 3057298 righe inserite.

[sorgenti]

mercoledì 14 settembre 2011

Strumenti per progettare i DB?

Un tempo usavo carta e matita per disegnare i db...
.. fino a che non sono diventati dei mostri di tabelle... (questa volta con MongoDB)


..adesso sotto consiglio di fede sono passato a OmniGraffle, i risultati non sono sempre buoni...

qualcuno mi consiglia un software più definito per lo scopo? (sotto Mac magari anche free... :) )

martedì 30 agosto 2011

Kill Postgres Connection


select procpid from pg_stat_activity where datname='<dbname>';


from bash: kill <procpid>

lunedì 23 maggio 2011

From Freedb.org to OrientDB - #4

#1 - #2 - #3

Download a big file about 170 Mb.
Uncompress  ... about 614 Mb and 2630481 file...

to speed up the importation are processed only 1000 files per folder.

sample porting schema from FreeDB to OrientDB:



import code




import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.schema.OProperty.INDEX_TYPE;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.io.FileUtils;

private String base = "/Users/marco/orientdb/";
private String root_dir = base + "/file_freedb/freedb-complete-20090101/";
private HashMap cache_year = new HashMap();
private HashMap cache_genre = new HashMap();

  private void import_data() {

        try {

            OServer server = OServerMain.create();
            server.startup(new File(base + "/file/conf.xml"));

            ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:" + base + "/freedb");
            if (!db.exists()) {
                db.create();
                System.out.println("create new DB");
            } else {
                db.delete();
                db.create();
                System.out.println("delete and create new DB");
            }


            FileFilter directoryFilter = new FileFilter() {

                public boolean accept(File file) {
                    return file.isDirectory();
                }
            };

            //default index on odocument
            db.begin();


            ODocument oArtist = new ODocument(db, "artist");
            oArtist.field("name", "Various", OType.STRING);
            oArtist.save();

            db.getMetadata().getSchema().getClass("artist").createProperty("name", OType.STRING).createIndex(INDEX_TYPE.FULLTEXT);
            db.getMetadata().getSchema().save();


            ODocument oTrack = new ODocument(db, "track");
            oTrack.field("title", "Various", OType.STRING);
            oTrack.save();

            db.getMetadata().getSchema().getClass("track").createProperty("title", OType.STRING).createIndex(INDEX_TYPE.FULLTEXT);
            db.getMetadata().getSchema().save();


            ODocument oGendr = new ODocument(db, "genre");
            oGendr.field("name", "Various", OType.STRING);
            oGendr.save();

            db.getMetadata().getSchema().getClass("genre").createProperty("name", OType.STRING).createIndex(INDEX_TYPE.UNIQUE);
            db.getMetadata().getSchema().save();


            ODocument oYear = new ODocument(db, "year");
            oYear.field("data", "19000101", OType.DATE);
            oYear.save();

            db.getMetadata().getSchema().getClass("year").createProperty("data", OType.DATE).createIndex(INDEX_TYPE.UNIQUE);
            db.getMetadata().getSchema().save();


            db.commit();


            File[] dirs = new File(root_dir).listFiles(directoryFilter);
            int i = 0;
            for (File dir : dirs) {

                if (!dir.isDirectory()) {
                    continue;
                }

                System.out.println("" + dir);

                int max_file_for_debug = 0;
                Collection files = FileUtils.listFiles(dir, null, true);
                for (File file : files) {
                    if (file.getName().startsWith(".")) {
                        continue;
                    }


                    try {
                        List lines = FileUtils.readLines(file);

                        db.begin();
                        ODocument oDisk = new ODocument(db, "disk");

                        ArrayList tracks = new ArrayList();

                        String titles = "";
                        String extd = "";
                        for (String line : lines) {

                            if (line.startsWith("# Disc length:")) {
                                String length = line.replaceAll("# Disc length:", "").replaceAll("seconds", "").replaceAll("secs", "").trim();

                                oDisk.field("Disc Length", length, OType.INTEGER);
                            }

                            if (line.startsWith("# Revision:")) {
                                String revision = line.replaceAll("# Revision:", "").trim();


                                oDisk.field("revision", revision, OType.INTEGER);
                            }


                            if (line.startsWith("#")) {
                                continue;
                            }

                            String ele[] = line.split("=");

                            if (ele == null || ele.length == 1) {
                                continue;
                            }

                            String key = ele[0];
                            String value = ele[1];


                            if (key.equals("DISKID")) {
                                oDisk.field(key.toLowerCase(), value, OType.STRING);
                            }

                            if (key.equals("DYEAR")) {
                                oDisk.field("year", check_and_create_year(value + "0101", db), OType.LINK);
                            }

                            if (key.equals("DGENRE")) {

                                oDisk.field("genre", check_and_create_genre(value, db), OType.LINK);
                            }

                            //concatenate multiple title lines
                            if (key.equals("DTITLE")) {
                                titles += value;
                            }

                            if (key.equals("EXTD")) {
                                extd += value;
                            }



                            //tracks list
                            if (key.startsWith("TTITLE")) {
                                oTrack = new ODocument(db, "track");
                                oTrack.field("n", key.replaceAll("TTITLE", ""), OType.INTEGER);

                                String tartist = "";


                                oTrack.field("title", getTitle(value));

                                tartist = getAuthor(value);

                                if (!tartist.equals("")) {

                                    oTrack.field("artist", check_and_create_artist(tartist, db), OType.LINK);
                                } else {
                                    oTrack.field("artist");
                                }


                                oTrack.save();
                                tracks.add(oTrack);

                            }

                        }

                        //add track_list
                        if (!tracks.isEmpty()) {
                            oDisk.field("tracks", tracks, OType.EMBEDDEDLIST);
                        }

                        //title and artist disk
                        if (!titles.equals("")) {

                            oDisk.field("title", getTitle(titles));
                            oDisk.field("artist", check_and_create_artist(getAuthor(titles), db), OType.LINK);

                        }

                        //title and artist disk
                        if (!extd.equals("")) {
                            oDisk.field("extd", extd);
                        }

                        oDisk.save();
                        db.commit();

                    } catch (IOException ex) {
                        System.out.println("ex (1):" + ex.getMessage() + ex.getStackTrace().toString());

                        for (StackTraceElement s : ex.getStackTrace()) {
                            System.out.println("" + s);
                        }

                        db.rollback();
                        continue;

                    }


                    i++;
                    if ((i >= 1000) && (i % 1000) == 1) {
                        System.out.println("\t" + file);
                        for (String s : db.getClusterNames()) {
                            System.out.println("cluster: " + s + " - " + db.countClusterElements(s));

                        }

                        //for debug max 1000 file for folder
                        break;
                    }

                }

            }


            db.close();

            //server
            server.shutdown();
        } catch (Exception ex) {
            System.out.println("ex (2):" + ex.getMessage() + ex.getStackTrace().toString());


            for (StackTraceElement s : ex.getStackTrace()) {
                System.out.println("" + s);
            }

        }

    }

    private ODocument check_and_create_artist(String name, ODatabaseDocumentTx db) {


        if (name.equals("")) {
            return null;
        }


        OSQLSynchQuery query = new OSQLSynchQuery("select from artist where name = ?");
        List result = db.command(query).execute(name);


        if (!result.isEmpty()) {
            return (ODocument) result.get(0);

        } else {

            ODocument oArtist = new ODocument(db, "artist");
            oArtist.field("name", /*a*/ name, OType.STRING);
            oArtist.save();

            return oArtist;
        }


    }

    private ODocument check_and_create_year(String year, ODatabaseDocumentTx db) {

        if (cache_year.containsKey(year)) {
            return cache_year.get(year);
        }


        OSQLSynchQuery query = new OSQLSynchQuery("select from year where data = ?");
        List result = db.command(query).execute(year);


        if (!result.isEmpty()) {
            cache_year.put(year, (ODocument) result.get(0));
            return (ODocument) result.get(0);

        } else {

            ODocument oYear = new ODocument(db, "year");
            oYear.field("data", year, OType.DATE);
            oYear.save();
            cache_year.put(year, oYear);

            return oYear;
        }


    }

    private ODocument check_and_create_genre(String genre, ODatabaseDocumentTx db) {

        if (cache_genre.containsKey(genre)) {
            return cache_genre.get(genre);
        }

        OSQLSynchQuery query = new OSQLSynchQuery("select from genre where name = ?");
        List result = db.command(query).execute(genre);

        if (!result.isEmpty()) {
            cache_genre.put(genre, (ODocument) result.get(0));
            return (ODocument) result.get(0);

        } else {

            ODocument oGenre = new ODocument(db, "genre");
            oGenre.field("name", genre, OType.STRING);
            oGenre.save();
            cache_genre.put(genre, oGenre);
            return oGenre;
        }


    }

    private String getTitle(String value) {


        if (value.indexOf("/") == -1) {
            return escape(value);
        }

        try {
            return escape(value.split("/")[0]);
        } catch (Exception e) {
            return "";
        }

    }

    private String getAuthor(String value) {

        if (value.indexOf("/") == -1) {
            return "";
        }

        if (value.split("/").length == 0) {
            return "";
        }

        try {
            return escape(value.split("/")[1]);
        } catch (Exception e) {
            return "";
        }


    }

    private String escape(String s) {
        if (s == null) {
            return s;
        }
        return s.trim().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("'", "\\\\'");
    }



Lib:

  • commons-io-2.0.1.jar
  • orient-commons-1.0rc2-SNAPSHOT.jar
  • orientdb-client-1.0rc2-SNAPSHOT.jar
  • orientdb-core-1.0rc2-SNAPSHOT.jar
  • orientdb-enterprise-1.0rc2-SNAPSHOT.jar
  • orientdb-server-1.0rc2-SNAPSHOT.jar
  • orientdb-tools-1.0rc2-SNAPSHOT.jar
  • persistence-api-1.0.jar

after several hours...


cluster: internal - 3
cluster: index - 882
cluster: default - 0
cluster: orole - 3
cluster: ouser - 3
cluster: artist - 43767
cluster: track - 155602
cluster: genre - 995
cluster: year - 114
cluster: disk - 11001



about 4GB of db...

Test Query:


first time:
query:select from artist name like 'Pink%' tot time:25692 ms
next:
query:select from artist name like 'Pink%' tot time:1646 ms

first time:
query:select from disk where artist.name like 'Pink%' tot time: 13388 ms
next:
query:select from disk where artist.name like 'Pink%' tot time: 4714 ms

first time:
query:select from disk where tracks contains ( artist.name like 'Pink%' ) tot time: 1628 ms
next:
query:select from disk where tracks contains ( artist.name like 'Pink%' ) tot time: 1481 ms

first/next time:
query:select from disk where year.data = '19780101' tot time: 906


giovedì 5 maggio 2011

OrientDB - Import da csv relazionali, relazioni, archiviare file e query #3


Proseguo la panoramica sulle funzionalità di OrientDb. Il miglior metodo per capire come funziona è quello di sperimentare. Genero dei dati test per simulare il funzionamento di un db relazionale social su file csv. Così costituito:

Utenti: elenco di utenti  id;nome;cognome;mail;password;  con relativo avatar collegato all'id.
lnk_utenti: collegamento tramite id degli utenti sugli utenti ( tipo amici).
post: id;utente_id;file;text;data;like[utenti];commenti[commento];tag[utenti]; dove i campi compresi tra [] identifica una lista di collegamenti.
commenti: id;utente_id;text;data;like[utenti];

Questa procedura mi permette di provare:
  • salvataggio in blocco dell'object
  • salvataggio nel db del file (avatar) vedi doc                         
  • collegamenti N:M su liste


package orientdbtest;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;

public class Social {

    public static void main(String[] args) {
        try {

            String base = "/Users/marco/orientdb/";

            OServer server = OServerMain.create();
            server.startup(new File(base + "/file/conf.xml"));

            ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:" + base + "/social").create();


            //elenco dei cluster
            for (String s : db.getClusterNames()) {
                System.out.println(s + " - " + db.countClusterElements(s));

            }



            //import UTENTI
            try {
                System.out.println("**** Start Import Utenti");
                long time = System.currentTimeMillis();

                BigFile big_file = new BigFile(base + "/file_social/utente.csv");

                boolean first_line = true;

                db.begin();

                for (String utente : big_file) {
                    if (first_line) {
                        first_line = false;
                        continue;
                    }

                    String[] utente_split = utente.split("\\;");

                    ODocument Outente = new ODocument(db, "Utenti");
                    Outente.field("id", utente_split[0], OType.SHORT);
                    Outente.field("nome", utente_split[1], OType.STRING);
                    Outente.field("cognome", utente_split[2], OType.STRING);
                    Outente.field("email", utente_split[3], OType.STRING);
                    Outente.field("password", utente_split[4], OType.STRING);

                    try {
                        File avatar = new File(base + "/file_social/avatar/" + utente_split[0] + ".jpg");

                        if (avatar.exists()) {
  
                            Outente.field("avatar", new ORecordBytes(db, FileUtils.readFileToByteArray(new File(base + "/file_social/avatar/" + utente_split[0] + ".jpg"))));
                            System.out.println("immagine trovata: " + base + "/file_social/avatar/" + utente_split[0] + ".jpg");
                        } else {
                            System.out.println("immagine " + base + "/file_social/avatar/" + utente_split[0] + ".jpg" + " non trovata");
                        }
                    } catch (IOException eFile) {
                        System.out.println("immagine " + base + "/file_social/avatar/" + utente_split[0] + ".jpg" + " non trovata");
                    }
                    Outente.save();

                }

                db.commit();

                System.out.println("tot time: " + (System.currentTimeMillis() - time));

            } catch (Exception e) {
                System.out.println("e1:" + e.getMessage() + e.getStackTrace().toString());
                db.rollback();
            }



            //import AMICI UTENTI

            try {
                System.out.println("**** Start Import Amici");


                long time = System.currentTimeMillis();


                BigFile big_file = new BigFile(base + "/file_social/lnk_utenti.csv");

                boolean first_line = true;



                for (String lnk_utenti : big_file) {
                    if (first_line) {
                        first_line = false;
                        continue;
                    }

                    String[] lnk_utenti_split = lnk_utenti.split("\\;");

                    db.begin();
                    //ricerco gli utente correlati e li aggancio uno agli altri
                    ODocument utente1 = (ODocument) db.query(new OSQLSynchQuery("select from utenti where id = '" + lnk_utenti_split[0] + "'")).get(0);
                    ODocument utente2 = (ODocument) db.query(new OSQLSynchQuery("select from utenti where id = '" + lnk_utenti_split[1] + "'")).get(0);

                    ArrayList lnk = new ArrayList();

                    if (utente1.field("lnk") != null) {
                        lnk = (ArrayList) utente1.field("lnk");
                    } else {
                        lnk = new ArrayList();
                    }

                    //verifico se nei lnk esiste già l'utente
                    boolean trovato = false;
                    if (!lnk.isEmpty()) {
                        for (ODocument check : lnk) {
                            System.out.println("check utente-1 id:" + check.field("id").toString() + " to: " + utente2.field("id").toString());
                            if (check.field("id").toString().equals(utente2.field("id").toString())) {
                                trovato = true;
                                continue;
                            }

                        }
                    }

                    if (!trovato) {

                        lnk.add(utente2);
                        utente1.field("lnk", lnk, OType.EMBEDDEDLIST);
                        System.out.println("utente-1 add: " + utente2.field("id"));
                        utente1.save();
                    }



                    if (utente2.field("lnk") != null) {
                        lnk = (ArrayList) utente2.field("lnk");
                    } else {
                        lnk = new ArrayList();
                    }


                    //verifico se nei lnk esiste già l'utente
                    trovato = false;
                    if (!lnk.isEmpty()) {
                        for (ODocument check : lnk) {
                            System.out.println("check utente-2 id:" + check.field("id").toString() + " to: " + utente1.field("id").toString());
                            if (check.field("id").toString().equals(utente1.field("id").toString())) {
                                trovato = true;
                                continue;
                            }

                        }
                    }
                    if (!trovato) {
                        lnk.add(utente1);
                        System.out.println("utente-2 add: " + utente1.field("id"));
                        utente2.field("lnk", lnk, OType.EMBEDDEDLIST);
                        utente2.save();
                    }


                    db.commit();

                }




                System.out.println("tot time: " + (System.currentTimeMillis() - time));


            } catch (Exception e) {
                System.out.println("e2:" + e.getMessage() + e.getStackTrace().toString());
                db.rollback();
            }


            for (String s : db.getClusterNames()) {
                System.out.println(s + " - " + db.countClusterElements(s));

            }




            try {
                System.out.println("**** Start Import Post");

                long time = System.currentTimeMillis();


                BigFile big_file = new BigFile(base + "/file_social/post.csv");

                boolean first_line = true;

                db.begin();

                for (String post : big_file) {
                    if (first_line) {
                        first_line = false;
                        continue;
                    }

                    String[] post_split = post.split("\\;");


                    //ricerco gli utente correlati e li aggancio uno agli altri
                    ODocument utente = (ODocument) db.query(new OSQLSynchQuery("select from utenti where id = '" + post_split[1] + "'")).get(0);

                    ODocument OPost = new ODocument(db, "Post");
                    OPost.field("id", post_split[0], OType.SHORT);
                    OPost.field("utente", utente, OType.EMBEDDED);
                    OPost.field("file", post_split[2], OType.STRING);
                    OPost.field("text", post_split[3], OType.STRING);
                    OPost.field("data", post_split[4], OType.STRING);

                    if (!post_split[5].equals("-")) {
                        String[] split_utenti = post_split[5].split("\\,");
                        ArrayList lnk = new ArrayList();
                        for (String ut : split_utenti) {
                            lnk.add((ODocument) db.query(new OSQLSynchQuery("select from utenti where id = '" + ut + "'")).get(0));
                        }
                        OPost.field("lnk", lnk, OType.EMBEDDEDLIST);
                    }


                    if (!post_split[7].equals("-")) {
                        String[] split_utenti = post_split[7].split("\\,");

                        ArrayList tag = new ArrayList();
                        for (String ut : split_utenti) {
                            tag.add((ODocument) db.query(new OSQLSynchQuery("select from utenti where id = '" + ut + "'")).get(0));
                        }
                        OPost.field("tag", tag, OType.EMBEDDEDLIST);
                    }


                    OPost.save();

                }

                db.commit();

                System.out.println("tot time: " + (System.currentTimeMillis() - time));


            } catch (Exception e) {
                System.out.println("e3:" + e.getMessage() + e.getStackTrace());
                db.rollback();
            }



            try {
                System.out.println("**** Start Import commenti");

                long time = System.currentTimeMillis();


                BigFile big_file = new BigFile(base + "/file_social/commenti.csv");

                boolean first_line = true;

                db.begin();

                for (String commenti : big_file) {
                    if (first_line) {
                        first_line = false;
                        continue;
                    }

                    String[] commenti_split = commenti.split("\\;");


                    //ricerco gli utente correlati e li aggancio uno agli altri
                    ODocument utente = (ODocument) db.query(new OSQLSynchQuery("select from utenti where id = '" + commenti_split[1] + "'")).get(0);

                    ODocument OCommenti = new ODocument(db, "commenti");
                    OCommenti.field("id", commenti_split[0], OType.SHORT);
                    OCommenti.field("utente", utente, OType.EMBEDDED);
                    OCommenti.field("text", commenti_split[2], OType.STRING);
                    OCommenti.field("data", commenti_split[3], OType.STRING);


                    if (!commenti_split[4].equals("-")) {

                        String[] split_utenti = commenti_split[4].split("\\,");

                        ArrayList lnk = new ArrayList();
                        for (String ut : split_utenti) {
                            lnk.add((ODocument) db.query(new OSQLSynchQuery("select from utenti where id = '" + ut + "'")).get(0));
                        }
                        OCommenti.field("lnk", lnk, OType.EMBEDDEDLIST);
                    }

                    OCommenti.save();

                }

                db.commit();

                System.out.println("tot time: " + (System.currentTimeMillis() - time));


            } catch (Exception e) {
                System.out.println("e5:" + e.getMessage() + e.getStackTrace());
                db.rollback();
            }



            try {
                System.out.println("**** Start Add Commenti/Utenti to Post");

                long time = System.currentTimeMillis();


                BigFile big_file = new BigFile(base + "/file_social/post.csv");

                boolean first_line = true;

                db.begin();

                for (String post : big_file) {
                    if (first_line) {
                        first_line = false;
                        continue;
                    }

                    String[] post_split = post.split("\\;");


                    //ricerco gli utente correlati e li aggancio uno agli altri
                    ODocument oPost = (ODocument) db.query(new OSQLSynchQuery("select from post where id = '" + post_split[0] + "'")).get(0);



                    if (!post_split[6].equals("-")) {

                        String[] split_commenti = post_split[6].split("\\,");
                        ArrayList lnk = new ArrayList();

                        for (String ut : split_commenti) {
                            lnk.add((ODocument) db.query(new OSQLSynchQuery("select from commenti where id = '" + ut + "'")).get(0));
                        }

                        oPost.field("commenti", lnk, OType.EMBEDDEDLIST);
                        oPost.save();
                    }



                }

                db.commit();

                System.out.println("tot time: " + (System.currentTimeMillis() - time));


            } catch (Exception e) {
                System.out.println("e3:" + e.getMessage() + e.getStackTrace());
                db.rollback();
            }



            try {
                System.out.println("**** Rimuovo tutti gli id");

                long time = System.currentTimeMillis();


                db.begin();

                String obj[] = {"utenti", "post", "commenti"};
                for (String o : obj) {
                    List docs = db.query(new OSQLSynchQuery("select from " + o));

                    for (ODocument doc : docs) {
                        doc.removeField("id");
                        doc.save();
                    }
                }

                db.commit();

                System.out.println("tot time: " + (System.currentTimeMillis() - time));


            } catch (Exception e) {
                System.out.println("e4:" + e.getMessage() + e.getStackTrace());
                db.rollback();
            }




            for (String s : db.getClusterNames()) {
                System.out.println(s + " - " + db.countClusterElements(s));

            }


            db.close();
            server.shutdown();
            
        } catch (Exception ex) {
            System.out.println("ex:" + ex.getMessage() + ex.getStackTrace().toString());
        }

        
        
    }
}



conclusa questa operazione di import delle info procedo ad eseguire qualche query per sperimentare il tutto.

con una query sola molto veloce riesco a:

  • estrarre carlo dall'elenco in base alla email
  • estrarre gli amici di carlo (prelevare l'avatar e salvarlo su disco)
  • estrarre tutti i post di un fede e ricavare tutti i commenti e like







package orientdbtest;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;

public class Main {

 
    public static void main(String[] args) {
        try {

            String base = "/Users/marco/orientdb/";

            OServer server = OServerMain.create();
            ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:" + base + "/social").open("admin", "admin");

            try {

                System.out.println("****** Start Query");

                long time = System.currentTimeMillis();

                ODocument carlo = (ODocument) db.query(new OSQLSynchQuery("select from utenti where email = 'carlo@email.it'")).get(0);
                System.out.println("Query dati di carlo - tot time: " + (System.currentTimeMillis() - time));
                System.out.println("nome:" + carlo.field("nome"));
                System.out.println("cognome:" + carlo.field("cognome"));

                //scrivo su file l'avatar presente, qui si può decidere cosa fare mandarlo sulla response o altro...
                File avatar = new File(base + "/test_avatar_di_carlo.jpg");
                FileUtils.writeByteArrayToFile(avatar, ((ORecordBytes) carlo.field("avatar")).toStream());
                System.out.println("Avatar estratto in:" + avatar);


                time = System.currentTimeMillis();
                List amici = db.query(new OSQLSynchQuery("select flatten(lnk) from utenti where email = 'carlo@email.it'"));
                System.out.println("Query elenco amici di carlo tot time: " + (System.currentTimeMillis() - time));
                for (ODocument amico : amici) {
                    System.out.println(amico.field("email"));
                }

                System.out.println();
                System.out.println();

                time = System.currentTimeMillis();
                amici = db.query(new OSQLSynchQuery("select flatten(lnk) from utenti where email = 'roberta@email.it'"));
                System.out.println("Query amici di amici di roberta - tot time: " + (System.currentTimeMillis() - time));


                for (ODocument amico : amici) {
                    System.out.print(amico.field("email") + " : ");

                    for (ODocument amico_di_amico : ((ArrayList) amico.field("lnk", OType.EMBEDDEDLIST))) {
                        System.out.print(amico_di_amico.field("email") + " ");
                    }

                    System.out.println();

                }



                System.out.println();
                System.out.println();





                time = System.currentTimeMillis();
                List mia_bacheca = db.query(new OSQLSynchQuery("select  * from post where utente.email = 'fede@email.it'"));
                System.out.println("Query la bacheca di fede tot time: " + (System.currentTimeMillis() - time));


                for (ODocument post : mia_bacheca) {
                    System.out.println("post: '" + post.field("text") + "' da " + ((ODocument) post.field("utente")).field("email"));
                    if (post.field("lnk") != null) {
                        ArrayList lnks = (ArrayList) post.field("lnk");
                        for (ODocument lnk : lnks) {
                            System.out.println("\t\tquesto post piace a: " + lnk.field("email"));
                        }
                    }


                    if (post.field("commenti") != null) {

                        ArrayList commenti = (ArrayList) post.field("commenti");
                        for (ODocument commento : commenti) {
                            System.out.println("\tcommento: '" + commento.field("text") + "' da " + ((ODocument) commento.field("utente")).field("email"));
                            if (commento.field("lnk") != null) {
                                ArrayList lnks = (ArrayList) commento.field("lnk");
                                for (ODocument lnk : lnks) {
                                    System.out.println("\t\tquesto commento piace a: " + lnk.field("email"));
                                }
                            }


                        }
                    }

                    System.out.println();

                }


                System.out.println("******* Stop Queries");


            } catch (Exception e) {
                System.out.println("e:" + e.getMessage() + e.getStackTrace().toString());
                db.rollback();
            } finally {


                db.close();
            }


            //server
            server.shutdown();
        } catch (Exception ex) {
            System.out.println("ex:" + ex.getMessage() + ex.getStackTrace().toString());
        }


    }
}



risultato:


****** Start Query
Query dati di carlo - tot time: 56
nome:carlo
cognome:rossi
Avatar estratto in:/Users/marco/orientdb/test_avatar_di_carlo.jpg
Query elenco amici di carlo tot time: 38
mauro@email.it
matteo@email.it
roberta@email.it
marco@email.it


Query amici di amici di roberta - tot time: 27
carlo@email.it : mauro@email.it matteo@email.it roberta@email.it 
mauro@email.it : carlo@email.it fede@email.it roberta@email.it 
fede@email.it : mauro@email.it roberta@email.it 


Query la bacheca di fede tot time: 56
post: 'una buona giornata a carlo e roberta' da fede@email.it
		questo post piace a: mauro@email.it
		questo post piace a: matteo@email.it
	commento: 'buona giornata a te' da mauro@email.it
		questo commento piace a: fede@email.it
		questo commento piace a: carlo@email.it
	commento: 'buona giornata a voi' da roberta@email.it
		questo commento piace a: carlo@email.it
		questo commento piace a: roberta@email.it

******* Stop Queries





note:
le query non funzionano così : email='carlo@email.it'. Ma così  email = 'carlo@email.it' (attenzione agli spazi)

altre puntate - #1 #2


lunedì 2 maggio 2011

OrientDB - Metodi di scrittura: ODocument e Pojo (Embedding in java) - #2

altre puntate: #1

prelevo un file di 10 mb da questo sito per avere dei dati di test per provare le performace di scrittura di questo db, ovvero prendo una classe la aggiungo ad un document e salvo il tutto.

Il file era troppo piccolo quindi lo copia e incollato su se stesso diverse volte ottenendo circa 720000  righe (adesso il mio file pesa 52 MB circa).

metoto ODocument con la classe ODatabaseDocumentTx

ecco il codice:


package orientdbtest;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import java.io.File;

public class Main {

    public static class GeoIp {

        String from;
        String to;
        Long lat;
        Long lng;
        String country;
        String state;

        public void setFrom(String from) {
            this.from = from;
        }

        public void setTo(String to) {
            this.to = to;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getFrom() {
            return from;
        }

        public String getTo() {
            return to;
        }

        public String getCountry() {
            return country;
        }

        public String getState() {
            return state;
        }

        public Long getLng() {
            return lng;
        }

        public Long getLat() {
            return lat;
        }

        public void setLng(Long lng) {
            this.lng = lng;
        }

        public void setLat(Long lat) {
            this.lat = lat;
        }
    }

    public static void main(String[] args) {
        try {

            String base = "/home/marco/Scrivania/orientdb/";

            OServer server = OServerMain.create();
            server.startup(new File(base + "/file/conf.xml"));

            ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:" + base + "/db").create();


            try {


                for (String s : db.getClusterNames()) {
                    System.out.println("name: " + s + " - " + db.countClusterElements(s));

                }

                db.begin();


                BigFile geoip_list = new BigFile(base + "/file/data/GeoIPCountryWhois.csv");


                long time = System.currentTimeMillis();


                long c = 0;
                for (String geoip_row : geoip_list) {
                    geoip_row = geoip_row.replaceAll("\"", "");
                    String[] s = geoip_row.split("\\,");
                    GeoIp geoIp = new GeoIp();
                    geoIp.setFrom(s[0]);
                    geoIp.setTo(s[1]);
                    geoIp.setLat(new Long(s[2]));
                    geoIp.setLng(new Long(s[3]));
                    geoIp.setCountry(s[4]);
                    geoIp.setState(s[5]);

                    ODocument doc = new ODocument(db);
                    doc.field("geoIp", geoIp);
                    doc.save();
                    if(c>10000 && c % 10000 == 0)
                        System.out.println(c);
                    c++;
                }



                db.commit();
                System.out.println("tot time: " + (System.currentTimeMillis() - time));
                System.out.println("commit:" + c);


            } catch (Exception e) {
                System.out.println("e:" + e.getMessage() + e.getStackTrace().toString());
                db.rollback();
            } finally {


                for (String s : db.getClusterNames()) {
                    System.out.println("name: " + s + " - " + db.countClusterElements(s));

                }

                db.close();
            }

            server.shutdown();
        } catch (Exception ex) {
            System.out.println("ex:" + ex.getMessage()+ ex.getStackTrace().toString());
        }


    }
}



qui la classe BigFile

lancio il tutto da console per evitare di usare troppa ram dalla ide visto che leggo il file con un iterator.

java -jar "/home/marco/netbeans-project/OrientDbTest/dist/OrientDbTest.jar" 

2011-04-29 05:29:02:098 INFO [OServer] OrientDB Server v1.0rc1-SNAPSHOT is starting up...
2011-04-29 05:29:07:325 INFO [OServerNetworkListener] Listening binary connections on 0.0.0.0:2424
2011-04-29 05:29:12:331 INFO [OServerNetworkListener] Listening http connections on 0.0.0.0:2480
2011-04-29 05:29:12:331 INFO [OServer] OrientDB Server v1.0rc1-SNAPSHOT is active.name: internal - 4
name: index - 0
name: default - 0
name: orole - 3
name: ouser - 3
20000
30000
40000
...
...
...
690000
700000
710000
tot time: 39482
commit:719600
name: internal - 4
name: index - 0
name: default - 719600
name: orole - 3
name: ouser - 3



...non male!!! inserite 719600 righe in 39 secondi tutto embeddato in un jar sul pc client....

se utilizzo il metodo POJO, ovvero OrientDB mappa la classe e salvo direttamente la classe mappata il tutto diventa molto più lento (forse perchè deve ricostruire tutto l'object in fase di salvataggio).

metodo POJO con la class ODatabaseObjectTx


package orientdbtest;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
import com.orientechnologies.orient.core.annotation.OVersion;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.type.ODocumentWrapper;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import javax.persistence.Id;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class Main {

    public static class GeoIp  {

          @Id
          private Object id;
          @OVersion
          private Object version;


        private String from;
        private String to;
        private Long lat;
        private Long lng;
        private String country;
        private String state;

        public void setFrom(String from) {
            this.from = from;
        }

        public void setTo(String to) {
            this.to = to;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getFrom() {
            return from;
        }

        public String getTo() {
            return to;
        }

        public String getCountry() {
            return country;
        }

        public String getState() {
            return state;
        }

        public Long getLng() {
            return lng;
        }

        public Long getLat() {
            return lat;
        }

        public void setLng(Long lng) {
            this.lng = lng;
        }

        public void setLat(Long lat) {
            this.lat = lat;
        }
    }

    public static void main(String[] args) {
        try {

            String base = "/home/marco/Scrivania/orientdb/";

            OServer server = OServerMain.create();
            server.startup(new File(base + "/file/conf.xml"));


                ODatabaseObjectTx db = new ODatabaseObjectTx("local:" + base + "/db").create();
                db.getEntityManager().registerEntityClass(GeoIp.class);
                
            try {


                for (String s : db.getClusterNames()) {
                    System.out.println("name: " + s + " - " + db.countClusterElements(s));

                }

                db.begin();


                BigFile geoip_list = new BigFile(base + "/file/data/GeoIPCountryWhois.csv");


                long time = System.currentTimeMillis();


                long c = 0;


                for (String geoip_row : geoip_list) {
                    geoip_row = geoip_row.replaceAll("\"", "");
                    String[] s = geoip_row.split("\\,");
                    GeoIp geoIp = new GeoIp();
                    geoIp.setFrom(s[0]);
                    geoIp.setTo(s[1]);
                    geoIp.setLat(new Long(s[2]));
                    geoIp.setLng(new Long(s[3]));
                    geoIp.setCountry(s[4]);
                    geoIp.setState(s[5]);
                    db.save(geoIp);
                    if(c>10000 && c % 10000 == 0)
                        System.out.println(c);
                    c++;
                }



                db.commit();
                System.out.println("tot time: " + (System.currentTimeMillis() - time));
                System.out.println("commit:" + c);


            } catch (Exception e) {
                System.out.println("e:" + e.getMessage() + e.getStackTrace().toString());
                db.rollback();
            } finally {


                for (String s : db.getClusterNames()) {
                    System.out.println("name: " + s + " - " + db.countClusterElements(s));

                }

                db.close();
            }


            server.shutdown();
        } catch (Exception ex) {
            System.out.println("ex:" + ex.getMessage()+ ex.getStackTrace().toString());
        }


    }
}




qui vengono indicate le velocità (colonna speed) in base al metodologia di salvataggio usato.


altre puntate: #1

venerdì 29 aprile 2011

OrientDB - primi passi di Embedding in java - #1

Sono sempre alla ricerca di DB in java da Embeddare in modo da provarli più rapidamente su NetBeans.

Dopo avere scaricato le lib della RC1 dal sito, prendo confidenza con lo strumento con qualche articolo su  RecordID e i Cluster

includo le lib nel mio progetto ed inizio a capire dalla documentazione come creare e gestire un db.




import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import java.io.File;

public class Main {

  public static void main(String[] args) {

    try {

          OServer server = OServerMain.create();
          server.startup(new File("/home/marco/file/conf.xml"));
          ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:/home/marco/db").create();
          server.shutdown();
    } catch (Exception ex) {
            System.out.println("ex:" + ex.getMessage());
    }

  }
}




il file conf.xml è questo:


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<orient-server>
<network>
<protocols>
    <protocol name="binary" implementation="com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary"/>
    <protocol name="http" implementation="com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb"/>
    </protocols>
    <listeners>
    <listener ip-address="0.0.0.0" port-range="2424-2430" protocol="binary"/>
    <listener ip-address="0.0.0.0" port-range="2480-2490" protocol="http"/>
    </listeners>
  </network>
    <users>
    <user name="root" password="test" resources="*"/>
    </users>
    <properties>
    <entry name="orientdb.www.path" value="/home/marco/Scrivania/orientdb/www/"/>
    <entry name="orientdb.config.file" value="/home/marco/Scrivania/orientdb/file/orientdb-server-config.xml"/>
    <entry name="server.cache.staticResources" value="false"/>
    <entry name="log.console.level" value="info"/>
<entry name="log.file.level" value="fine"/>
    </properties>
</orient-server>



a questo punto il db è creato per accederci bisogna utilizzare questa connessione:

ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:/home/marco/db").open("admin", "admin");


di default viene creato l'utente admin admin per l'accesso del db in locale.


con questa funzionalità è possibile vedere quali cluster sono presenti, gli elementi contenuti e info sull'utente in uso sul nostro nuovo db:

System.out.println("closed:" + db.isClosed());
OUser user = db.getUser();
System.out.println("user:" + user.getName());
System.out.println("password:" + user.getPassword());

for (String s : db.getClusterNames()) {
           System.out.println("cluster: " + s + " - " + db.countClusterElements(s));

}




Salviamo qualcosa


          try {
db.begin();

ODocument persona = new ODocument(db, "Persona");
persona.field("nome", "marco");
persona.field("cognome", "bianchi");
persona.save();

persona = new ODocument(db, "Persona");
persona.field("nome", "carlo");
persona.field("cognome", "rossi");
persona.save();

db.commit();
} catch (Exception e) {
System.out.println("ex:" + e.getMessage());
db.rollback();
} finally {
db.close();
}



Eseguiamo la query ed estraiamo i valori appena scritti


List persone = db.query(new OSQLSynchQuery("select from Persona"));

for (ODocument persona : persone) {
System.out.println( persona.field("nome") + " " +  persona.field("cognome"));
}

non male vero?

se rieseguite il codice per elencare i cluster vedrete:

Persona : 2


E' possibili correlare anche gli object in questo modo inserendo documenti in documenti:




try {
db.begin();

ODocument persona = new ODocument(db, "Persona");
persona.field("nome", "marco");
persona.field("cognome", "bianchi");

ODocument auto = new ODocument(db, "Auto");
auto.field("marco", "seat ibiza");
auto.field("cilindrata", "1444");
persona.field("auto",auto);


persona.save();

persona = new ODocument(db, "Persona");
persona.field("nome", "carlo");
persona.field("cognome", "rossi");

auto = new ODocument(db, "Auto");
auto.field("marco", "fiat punto");
auto.field("cilindrata", "1245");
persona.field("auto",auto);

persona.save();

db.commit();
} catch (Exception e) {
System.out.println("ex:" + e.getMessage());
db.rollback();
} finally {
db.close();
}





e ancora più complesso inserendo una lista di valori in un field sotto forma di List:




try {
db.begin();

ODocument persona = new ODocument(db, "Persona");
persona.field("nome", "marco");
persona.field("cognome", "bianchi");

ArrayList mezzi_list = new ArrayList();

ODocument auto = new ODocument(db, "Auto");
auto.field("marco", "seat ibiza");
auto.field("cilindrata", "1444");

mezzi_list.add(auto);

auto = new ODocument(db, "Auto");
auto.field("marco", "fiat punto");
auto.field("cilindrata", "1245");

mezzi_list.add(auto);

persona.field("mezzi",mezzi_list);

persona.save();

db.commit();
} catch (Exception e) {
System.out.println("ex:" + e.getMessage());
db.rollback();
} finally {
db.close();
}




mercoledì 30 marzo 2011

postgresql : eseguire una query da console

..mai che mi ricordo questo comodissimo comando da console

psql <nomedb> -c "select * from..." > file.txt

oppure
<nomedb> -c "update..."