added command-line options
[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 my $sql = qq{
20         select
21                 md5(link) as _id,
22                 items.*
23         from items
24         where id > ?
25         order by id asc
26         limit 100000
27 };
28
29 my $sql_tags = qq{
30 select
31         items_userdata.item_id,
32         value_long as tags,
33         timestamp
34 from items_userdata
35 join published_items p
36         on items_userdata.item_id = p.item_id and label='tags'
37 where
38         items_userdata.item_id > ?
39 order by items_userdata.item_id asc
40 };
41
42 my $conn  = MongoDB::Connection->new;
43 my $db    = $conn->get_database( $database );
44 $db->drop if $debug;
45 my $items = $db->get_collection( 'items' );
46
47 $items->ensure_index( { id => 1 } );
48
49 # > db.items.find().sort({item_id:-1}).limit(1);
50 my $last = $items->query()->sort({ 'id' => -1 })->limit(1)->next;
51 warn dump( $last );
52 my $last_item_id = $last->{id} || 0;
53
54 print "Fetching items from $dbi id > $last_item_id\n";
55
56 my $sth = $dbh->prepare($sql);
57 $sth->execute( $last_item_id );
58
59 warn dump( $sth->{NAME} );
60
61 print "found ",$sth->rows," items to process...\n";
62
63 while (my $row = $sth->fetchrow_hashref() ) {
64
65         map { $row->{$_} * 1 } grep { m/id/ && $row->{$_} =~ /^\d+$/ } keys %$row;
66         $items->insert( $row );
67 }
68
69 __END__
70
71 my $sth_tags = $dbh->prepare($sql_tags);
72 $sth_tags->execute( $last_item_id );
73 print "found ",$sth_tags->rows, " tags found...\n";
74
75 my $count = 0;
76
77 my $row_tags = $sth_tags->fetchrow_hashref();
78
79 my @join = ( 'id' => 'item_id' );
80