Advertisement
Guest User

Import Wikipedia category graph

a guest
Sep 29th, 2011
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.05 KB | None | 0 0
  1. package importazione;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataInputStream;
  5. import java.io.FileInputStream;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.util.Map;
  9.  
  10. import org.neo4j.graphdb.DynamicRelationshipType;
  11. import org.neo4j.graphdb.index.BatchInserterIndex;
  12. import org.neo4j.graphdb.index.BatchInserterIndexProvider;
  13. import org.neo4j.graphdb.index.IndexHits;
  14. import org.neo4j.helpers.collection.MapUtil;
  15. import org.neo4j.index.impl.lucene.LuceneBatchInserterIndexProvider;
  16. import org.neo4j.kernel.impl.batchinsert.BatchInserter;
  17. import org.neo4j.kernel.impl.batchinsert.BatchInserterImpl;
  18.  
  19. public class importa {
  20.  
  21.     /**
  22.      * @param args
  23.      * @throws IOException
  24.      */
  25.         public static void main(String[] args) throws IOException {
  26.         BatchInserter inserter = new BatchInserterImpl( "/media/Ubuntu/wikipedia/batchcreating" );
  27.         BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider(inserter);
  28.         BatchInserterIndex IDs = indexProvider.nodeIndex( "IDs", MapUtil.stringMap( "type", "exact" ) );
  29.         BatchInserterIndex names = indexProvider.nodeIndex( "names", MapUtil.stringMap( "type", "exact" ) );
  30.  
  31.  
  32.         IDs.setCacheCapacity( "ID", 100000 );
  33.         names.setCacheCapacity( "name", 100000 );
  34.  
  35.         // BEFORE using this brogram is necessary to use the command sed 's/),(/\n/g' *.sql
  36.         //on the two extracted .sql files
  37.         Lettore l=new Lettore("/media/Ubuntu/wikipedia/enwiki-20110901-page.sql");
  38.  
  39.  
  40.         boolean iniziato=false;
  41.         for(String riga:l){
  42.             if(!iniziato){
  43.                 if(riga.contains("INSERT INTO"))
  44.                     iniziato=true;
  45.                 continue;
  46.  
  47.             }
  48.             if (riga.contains("INSERT INTO `page` VALUES ("))
  49.                 riga=riga.substring("INSERT INTO `page` VALUES (".length());
  50.             //mi interrompo se sono alla fine
  51.             if (riga.startsWith("/*!40000 ALTER TABLE")) break;
  52.             int ns=Integer.parseInt(riga.split(",")[1]);
  53.             if (ns!=0 && ns!=14) continue;
  54.             int id=Integer.parseInt(riga.split(",")[0]);
  55.             String parte=riga.split(",'")[1];
  56.             //la pagina sulla virgola darebbe problemi, basta identificarla con il suo id e trattarla a parte
  57.             String nome;
  58.             if (id==64494)
  59.                 nome=",";
  60.             else
  61.                 nome=parte.substring(0,parte.length()-1);
  62.             nome=nome.replace("\\'", "'");
  63.  
  64.             if (ns==0){
  65.                 //è una pagina
  66.                 //se è una disambiguazione la salto
  67.                 if(nome.contains("(disambiguation)")) continue;
  68.                 Map<String, Object> properties = MapUtil.map("name", nome,"ID",new Integer(id),"type","page" );
  69.                 long node = inserter.createNode( properties );
  70.                 IDs.add( node, MapUtil.map("ID",new Integer(id)));
  71.                 names.add( node, MapUtil.map("name",nome));
  72.                 System.out.println("pagina "+nome+"["+id+"]");
  73.             }
  74.             if (ns==14){
  75.                 //è una categoria
  76.                 //se è sicuramente non significativa, la salto
  77.                 if (nome.contains("_redirects")) continue;
  78.                 if (nome.contains("Articles_"))  continue;
  79.                 if (nome.contains("_articles")) continue;
  80.                 if (nome.contains("Pages_with_"))  continue;
  81.                 if (nome.contains("Redirects_"))  continue;
  82.                 if (nome.contains("_disambiguation_"))  continue;
  83.                 if (nome.contains("Disambiguation_"))  continue;
  84.                 if (nome.contains("Start-Class_"))  continue;
  85.                 Map<String, Object> properties = MapUtil.map("name", nome,"ID",new Integer(id),"type","cat" );
  86.                 long node = inserter.createNode( properties );
  87.                 IDs.add( node, MapUtil.map("ID",new Integer(id)));
  88.                 names.add( node, MapUtil.map("name",nome));
  89.                 System.out.println("categoria "+nome+"["+id+"]");
  90.             }
  91.  
  92.         }
  93.         l.chiudi();
  94.  
  95.         names.setCacheCapacity("name", 400000);
  96.  
  97.  
  98.  
  99.         l=new Lettore("/media/Ubuntu/wikipedia/enwiki-20110901-categorylinks.sql");
  100.  
  101.  
  102.         iniziato=false;
  103.         //mi servono per evitare di recuperare ogni volta lo stesso id
  104.         int oldid=-1;
  105.         IndexHits<Long> oldlista = null;
  106.  
  107.         for(String riga:l){
  108.  
  109.             if(!iniziato){
  110.                 if(riga.contains("INSERT INTO"))
  111.  
  112.                     iniziato=true;
  113.                 continue;
  114.  
  115.             }
  116.             if (riga.contains("INSERT INTO `categorylinks` VALUES ("))
  117.                 riga=riga.substring("INSERT INTO `categorylinks` VALUES (".length());
  118.             //mi interrompo se sono alla fine
  119.             if (riga.startsWith("/*!40000 ALTER TABLE")) break;
  120.  
  121.             int id=Integer.parseInt(riga.split(",")[0]);
  122.             String parte=riga.split(",'")[1];
  123.  
  124.             String nome=parte.substring(0,parte.length()-1);
  125.             nome=nome.replace("\\'", "'");
  126.  
  127.  
  128.             //se è sicuramente non significativa, la salto
  129.             if (nome.contains("_redirects")) continue;
  130.             if (nome.contains("Articles_"))  continue;
  131.             if (nome.contains("_articles")) continue;
  132.             if (nome.contains("Pages_with_"))  continue;
  133.             if (nome.contains("Redirects_"))  continue;
  134.             if (nome.contains("_disambiguation_"))  continue;
  135.             if (nome.contains("Disambiguation_"))  continue;
  136.             if (nome.contains("Start-Class_"))  continue;
  137.             if (nome.contains("All_pages_"))  continue;
  138.             if (nome.contains("Use_mdy_"))  continue;
  139.             if (nome.contains("Unverifiable_"))  continue;
  140.             if (nome.contains("-protected_pages"))  continue;
  141.             if (nome.contains("semi-protected"))  continue;
  142.             if (nome.contains("Pages_containing_"))  continue;
  143.             if (nome.contains("_stubs"))  continue;
  144.  
  145.  
  146.             //recupero l'elemento contenuto
  147.             //se è quello di prima non ripeto il recupero
  148.             IndexHits<Long> lista;
  149.             if(id==oldid){
  150.                 lista=oldlista;
  151.             }
  152.             else{
  153.                 lista = IDs.get("ID", id);
  154.                 oldlista=lista;
  155.                 oldid=id;
  156.             }
  157.  
  158.             //se la lista non è vuota, contiene un solo elemento
  159.             if(lista.hasNext()){
  160.                 Long idelem = lista.next();
  161.                 //ora recupero la categoria che ha quel nome
  162.                 for(Long idcat:names.get("name", nome)){
  163.                     //potrebbe essere una categoria o una pagina con lo stesso nome
  164.                     if(inserter.getNodeProperties(idcat).get("type").equals("cat")){
  165.                         //ho recuperato idcat e idelem, devo capire se idelem rappresenta una pagina o un'altra categoria
  166.                         if(inserter.getNodeProperties(idelem).get("type").equals("cat")){
  167.                             //è una categoria
  168.                             inserter.createRelationship(idelem, idcat, DynamicRelationshipType.withName( "SUBCATEGORYOF" ),null );
  169.                             if(Math.random()<0.1)
  170.                                 System.out.println(riga);                       }
  171.                         else{
  172.                             //è una pagina
  173.                             if(Math.random()<0.1)
  174.                                 System.out.println(riga);
  175.                             inserter.createRelationship(idelem, idcat, DynamicRelationshipType.withName( "BELONGSTO" ),null );
  176.  
  177.                         }
  178.  
  179.                     }
  180.                 }
  181.             }
  182.             else
  183.                 continue;
  184.  
  185.  
  186.  
  187.         }
  188.         // Make sure to shut down the index provider
  189.         indexProvider.shutdown();
  190.         inserter.shutdown();
  191.     }
  192.  
  193. }
  194.  
  195. class Lettore implements Iterable<String> {
  196.  
  197.     private String risorsa;
  198.     private BufferedReader in;
  199.     private boolean isURL;
  200.     private boolean isFolder;
  201.     private int riga;
  202.  
  203.     public static void main(String argc[]) throws IOException {
  204.         // Lettore l=new Lettore("mio_gioco/edit.dat");
  205.         // System.out.println(l);
  206.         // Lettore d=l.creaDa("test.map");
  207.         // System.out.println(d);
  208.  
  209.         Lettore f = new Lettore("mio_gioco/cells");
  210.         System.out.println(f);
  211.         System.out.println(f.isFolder);
  212.  
  213.         Lettore nf = f.creaDa("city.png");
  214.         System.out.println(nf);
  215.         System.out.println(nf.isFolder);
  216.  
  217.     }
  218.  
  219.     /**
  220.      * Crea un lettore che punti al file, alla cartella o all'URL indicati
  221.      *
  222.      * @param indirizzo
  223.      *            il percorso assoluto o relativo nel filesystem o l'URL
  224.      * */
  225.     public Lettore(String indirizzo) {
  226.         // il lettore deve fare riferimento a un file o un URL,
  227.         // e deve poter creare un lettore partendo da un indirizzo relativo
  228.         // gestendo le diverse scritture dei file e semplificandone l'uso
  229.  
  230.         this.risorsa = indirizzo;
  231.  
  232.         if (risorsa.startsWith("http://")) {
  233.             this.isURL = true;
  234.             if (risorsa.endsWith("/"))
  235.                 isFolder = true;
  236.  
  237.         } else {
  238.             this.isURL = false;
  239.             risorsa = (new File(indirizzo)).getAbsolutePath();
  240.             if (new File(risorsa).isDirectory()) {
  241.                 isFolder = true;
  242.                 return;
  243.             }
  244.         }
  245.     }
  246.  
  247.     public Lettore(File cartella) throws IOException {
  248.         this(cartella.getAbsolutePath());
  249.     }
  250.  
  251.     /**
  252.      * Restituisce un oggetto di tipo BufferedReader per la risorsa che
  253.      * rappresenta La risorsa potrebbe non essere accessibile o essere una
  254.      * cartella, quindi posso lanciare delle eccezioni
  255.      * */
  256.     public BufferedReader getReader() throws MalformedURLException, IOException {
  257.         if (in != null)
  258.             return in;
  259.         if (this.isURL) {
  260.             return new BufferedReader(new InputStreamReader(
  261.                     (new URL(risorsa)).openStream()));
  262.         } else {
  263.  
  264.             FileInputStream fstream = new FileInputStream(risorsa);
  265.             DataInputStream dis = new DataInputStream(fstream);
  266.             in = new BufferedReader(new InputStreamReader(dis));
  267.             return in;
  268.         }
  269.  
  270.     }
  271.  
  272.     /**
  273.      * Apre un BufferedReader, se non era già aperto, e legge la prima stringa
  274.      * dal file a ogni chiamata legge la successiva stringa o restituisce null
  275.      * se arriva alla fine
  276.      * */
  277.     public String leggi() throws IOException {
  278.         if (in == null) {
  279.             if (this.isURL) {
  280.                 in = new BufferedReader(new InputStreamReader(
  281.                         (new URL(risorsa)).openStream()));
  282.             } else {
  283.  
  284.                 FileInputStream fstream = new FileInputStream(risorsa);
  285.                 DataInputStream dis = new DataInputStream(fstream);
  286.                 in = new BufferedReader(new InputStreamReader(dis));
  287.             }
  288.         }
  289.         riga++;
  290.         return in.readLine();
  291.  
  292.     }
  293.  
  294.     public String toString() {
  295.         if (!this.isURL && this.isFolder) {
  296.             return risorsa + File.separatorChar;
  297.         }
  298.         return risorsa;
  299.     }
  300.  
  301.     /**
  302.      * crea un altro Lettore partendo da un percorso che può essere relativo a
  303.      * quello attuale
  304.      * */
  305.     public Lettore creaDa(String indirizzo) {
  306.         // vari casi possibili:
  307.  
  308.         // È un URL completo
  309.         if (indirizzo.startsWith("http://"))
  310.             return new Lettore(indirizzo);
  311.         // È un percorso assoluto di file su filesystem tipo UNIX
  312.         if (File.separatorChar == '/' && indirizzo.matches("/.+"))
  313.             return new Lettore(indirizzo);
  314.         // È un percorso assoluto di file su filesystem di tipo DOS (Windows)
  315.         if (File.separatorChar == '\\' && indirizzo.matches("[a-zA-Z]:\\.+"))
  316.             return new Lettore(indirizzo);
  317.  
  318.         // la parte importante:indirizzo relativo
  319.  
  320.         // il mio indirizzo è un URL o in un filesystem unix
  321.         if (this.isURL() || risorsa.startsWith("/")) {
  322.             String folder;
  323.             if (isFolder)
  324.                 folder = risorsa;
  325.             else
  326.                 folder = risorsa.substring(0, risorsa.lastIndexOf('/'));
  327.  
  328.             // converto le barre \ in /
  329.             return new Lettore(folder + "/" + indirizzo.replace('\\', '/'));
  330.         }
  331.  
  332.         // il mio indirizzo è un file in un filesystem windows
  333.         if (risorsa.matches("[a-zA-Z]:\\.+")) {
  334.             String folder;
  335.             if (isFolder)
  336.                 folder = risorsa;
  337.             else
  338.                 folder = risorsa.substring(0, risorsa.lastIndexOf('\\'));
  339.             return new Lettore(folder + "\\" + indirizzo.replace('/', '\\'));
  340.         }
  341.  
  342.         // se non sono ancora ritornato, mi trovo qui e c'è stato un errore
  343.         // TODO come gestirlo?
  344.         return null;
  345.  
  346.     }
  347.  
  348.     public boolean isURL() {
  349.         return isURL;
  350.     }
  351.  
  352.     public int getNumeroRiga() {
  353.         return this.riga;
  354.     }
  355.  
  356.     /**
  357.      * restituisce il percorso relativo a quello corrente, se possibile, di un
  358.      * percorso dato altrimenti quello assoluto
  359.      *
  360.      * @throws IOException
  361.      *             se il file non esiste
  362.      * */
  363.     public String getPercorsoRelativo(String percorso) throws IOException {
  364.         // mi basta controllare che il percorso assoluto della cartella mio file
  365.         // contenga quello della cartella del percorso dato
  366.         String percorsoAssoluto = this.creaDa(percorso).toString();
  367.  
  368.         String cartellaAssoluta = "";
  369.  
  370.         if (!this.isFolder && (this.isURL || File.separatorChar == '/'))
  371.             cartellaAssoluta = risorsa.substring(0, risorsa.lastIndexOf('/'));
  372.         if (!this.isFolder && (!this.isURL && File.separatorChar == '\\'))
  373.             cartellaAssoluta = risorsa.substring(0, risorsa.lastIndexOf('\\'));
  374.  
  375.         // aggiungo +1 per lo \ o lo /, che devono essere eliminati
  376.         if (this.risorsa.startsWith(cartellaAssoluta))
  377.             return percorsoAssoluto.substring(cartellaAssoluta.length() + 1);
  378.         else
  379.             return percorsoAssoluto;
  380.     }
  381.  
  382.     public void chiudi() throws IOException {
  383.         in.close();
  384.     }
  385.  
  386.     public boolean isCartella() {
  387.         return isFolder;
  388.     }
  389.  
  390.     public Iterator<String> iterator() {
  391.  
  392.         try {
  393.             return new Iteratore(this);
  394.         } catch (IOException e) {
  395.             // eccezione: file non apribile oppure già iterato.
  396.             // lo riapro, per gestire il secondo caso
  397.             try {
  398.                 return new Iteratore(new Lettore(this.risorsa));
  399.             } catch (IOException e1) {
  400.                 e1.printStackTrace();
  401.                 return null;
  402.             }
  403.         }
  404.     }
  405.  
  406.     class Iteratore implements Iterator {
  407.         String riga = "";
  408.         Lettore l;
  409.  
  410.         public Iteratore(Lettore lettore) throws IOException {
  411.             l = lettore;
  412.             riga = l.leggi();
  413.         }
  414.  
  415.         public boolean hasNext() {
  416.             return (riga != null);
  417.         }
  418.  
  419.         public String next() {
  420.             if (riga == null)
  421.                 throw new NoSuchElementException(
  422.                         "Fine del file: non posso andare avanti!");
  423.             String temp = riga;
  424.             try {
  425.                 riga = l.leggi();
  426.             } catch (IOException e) {
  427.                 // TODO Auto-generated catch block
  428.                 e.printStackTrace();
  429.             }
  430.             return temp;
  431.         }
  432.  
  433.         /**
  434.          * Metodo non supportato lancia sempre un'eccezione
  435.          * */
  436.         public void remove() {
  437.             // operazione non supportata
  438.             throw new UnsupportedOperationException(
  439.                     "Errore nell'iteratore del Lettore: non posso rimuovere elementi! file:"
  440.                             + l.toString());
  441.         }
  442.  
  443.     }
  444. }
  445.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement