first experiment to transfer data from Reblog to MongoDB
[mongodb-experiments.git] / reblog2mongodb.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4 use DBI;
5 use MongoDB;
6 use Data::Dump qw/dump/;
7
8 $|++;
9
10 my $debug = @ARGV ? 1 : 0;
11
12 my $database = 'reblog';
13
14 my $dbi = "DBI:mysql:database=$database";
15 $dbi .= ";host=127.0.0.1;port=13306";   # XXX over ssh
16
17 my $dbh = DBI->connect($dbi,"","",{ RaiseError => 1 });
18
19 $dbh->do(qq{
20         create temporary table published_items as
21         select
22                 item_id
23         from
24                 items_userdata
25         where
26                 label = 'published' and
27                 value_numeric = 1
28 });
29
30 my $sql = qq{
31         select
32                 i.id as item_id,
33 --              i.guid as _id,
34 --              i.link as _id,
35                 i.*,
36                 f.url as feed_url,
37                 f.title as feed_title,
38                 f.link as feed_link,
39                 f.description as feed_description
40         from items i
41         join published_items p on i.id = p.item_id
42         join feeds f on i.feed_id = f.id
43         where i.id > ?
44         order by i.id asc
45         limit 1000
46 };
47
48 my $sql_tags = qq{
49 select
50         items_userdata.item_id,
51         value_long as tags,
52         timestamp
53 from items_userdata
54 join published_items p
55         on items_userdata.item_id = p.item_id and label='tags'
56 where
57         items_userdata.item_id > ?
58 order by items_userdata.item_id asc
59 };
60
61 my $conn  = MongoDB::Connection->new;
62 my $db    = $conn->get_database( $database );
63 my $items = $db->get_collection( 'items' );
64
65 my $last_row = 0;
66 $last_row = 0 if $debug;
67
68 print "Fetching items from $dbi id > $last_row\n";
69
70 my $sth = $dbh->prepare($sql);
71 $sth->execute( $last_row );
72
73 warn dump( $sth->{NAME} );
74
75 print "found ",$sth->rows," items to process...\n";
76
77 my $sth_tags = $dbh->prepare($sql_tags);
78 $sth_tags->execute( $last_row );
79 print "found ",$sth_tags->rows, " tags found...\n";
80
81 my $count = 0;
82
83 my $row_tags = $sth_tags->fetchrow_hashref();
84
85 while (my $row = $sth->fetchrow_hashref() ) {
86         my $_id = $row->{_id} || "c$count";
87         $_id =~ s{\W+}{_}g;
88         $_id =~ s{_+$}{};
89
90         my $doc = $row;
91 #       $row->{_id} = $id;
92
93         while ( $row_tags && $row_tags->{item_id} < $row->{item_id} ) {
94                 $row_tags = $sth_tags->fetchrow_hashref();
95                 warn "## got tags: ",dump( $row_tags ) if $debug;
96         }
97
98         if ( $row_tags && $row_tags->{item_id} == $row->{item_id} ) {
99                 $doc->{tags} = [ split(/\s+/, $row_tags->{tags} ) ];
100                 warn "++ ",$row->{item_id}, dump( $row->{tags} ),$/;
101         }
102
103         $items->insert( $doc );
104
105         $last_row = $row->{id};
106         $count++;
107
108 }
109