Manual:MWDumper/ja

From mediawiki.org
This page is a translated version of the page Manual:MWDumper and the translation is 35% complete.
Important: Beware that MWDumper has not been actively maintained since the mid-2000s, and may or may not work with current deployments. Apparently, it can't be used to import into MediaWiki 1.31 or later.

MWDumper is a tool written in Java for extracting sets of pages from a MediaWiki dump file. For example, it can load Wikipedia's content into MediaWiki.

MWDumper can read MediaWiki XML export dumps (version 0.3, minus uploads), perform optional filtering, and output back to XML or to SQL statements to add things directly to a database in 1.4 or 1.5 schema.

While this can be used to import XML dumps into a MediaWiki database, it might not be the best choice for small imports (say, 100 pages or less). See Manual:XMLダンプの取り込み for an overview.

Where to find it

To import current XML export dumps, you'll need an up-to-date build of MWDumper...

You can build an up to date MWDumper from source. (See #How to build MWDumper from source, below).

If you have Docker and do not want to build it yourself, you can use the following Docker image which does it for you: https://hub.docker.com/r/ueland/mwdumper/

使用法

Prerequisites for imports via MWDumper

Before using mwdumper, your page, text, revision and redirect tables must be empty. To empty them, do this (note that this will wipe out an existing wiki):

  • In SQL: USE wikidb; TRUNCATE TABLE page; TRUNCATE TABLE text; TRUNCATE TABLE revision; TRUNCATE TABLE redirect;
  • In maintenance directory: php rebuildall.php

Import dump files with MWDumper

直接データベースのインポートをするためのサンプルのコマンドラインです:

  java -jar mwdumper.jar --format=sql:1.25 pages_full.xml.bz2 |
    mysql -u <username> -p <databasename>

または

  cd mwdumper/src
  javac org/mediawiki/dumper/Dumper.java
  cd ..
  java -classpath ./src org.mediawiki.dumper.Dumper --format=sql:1.25 pages_full.xml.bz2 |
    mysql -u <username> -p <databasename>

Note: javac org/mediawiki/dumper/Dumper.java will throw errors and this will have to be debugged
     ./org/mediawiki/dumper/filters/predicates/AdHocListFilter.java:5: error: 
     package com.google.common.base does not exist
     import com.google.common.base.Splitter;
 
A third party developer has added features to output in a tab delimited format for processing large dumps. The compiled version is mwdumper.jar and the code for the project is mwdumper. To use the update you have to specify a separate output file for pages since you don't want to have the two tab delimited output files dumped together. This was done specifically for processing the large Wikipedia Dumps using Hadoop. Usage is shown below:
cat train.xml | java -jar mwdumper.jar --format=flatfile:pages_output_file.txt - --quiet > train.txt

ヒント:インポートが成功するために テーブル群 page, revision, text は空でなければなりません。

This command will keep going even if MySQL reports an error. This is probably not what you want - if you use the direct connection to MySQL, the import will stop when errors occur.
If you nohup a mwdumper command, be sure to use the --quiet option.

文字エンコーディング上の注意

データベースがutf8でエンコードされたテキストを要求することを確認して下さい。データベースがlatin1(MySQLのデフォルト)を要求する場合、mwdumper の出力を直接使用する場合テーブルで不正な文字を取得します。これをする一つの方法は上記のサンプルで --default-character-set=utf8 を MySQL に渡すことです。

If you want to use the output of mwdumper in a JDBC URL, you should use set characterEncoding=utf8 in the query string.

Also make sure that your MediaWiki tables use CHARACTER SET=binary. Otherwise, you may get error messages like Duplicate entry in UNIQUE Key 'name_title' because MySQL fails to distinguish certain characters.

複雑なフィルタリング

複数の出力ファイルを生み出すために複雑なフィルタリングをすることもできます:

  java -jar mwdumper.jar \
    --output=bzip2:pages_public.xml.bz2 \
      --format=xml \
      --filter=notalk \
      --filter=namespace:\!NS_USER \
      --filter=latest \
    --output=bzip2:pages_current.xml.bz2 \
      --format=xml \
      --filter=latest \
    --output=gzip:pages_full_1.25.sql.gz \
      --format=sql:1.25 \
    --output=gzip:pages_full_1.5.sql.gz \
      --format=sql:1.5 \
    --output=gzip:pages_full_1.4.sql.gz \
      --format=sql:1.4 \
    pages_full.xml.gz

裸のパラメーターは XML 入力を読み込むためにファイルとして解釈されます; "-"もしくは空の値が与えられた場合、入力は標準入力から読み込まれます。".gz"もしくは".bz2"拡張子を持つ入力ファイルはそれぞれgzipもしくはbzip2ストリームとして展開されます。

7-zip、.7zファイルの内部展開はまだサポートされていません; p7zipの7zaを通してファイルをそれらのファイルをパイプできます:

  7za e -so pages_full.xml.7z |
    java -jar mwdumper.jar --format=sql:1.25 |
    mysql -u <username> -p <databasename>

パラメーターが与えられない場合の既定値です:

  • 標準入力から圧縮解除前のXMLを読み込む
  • 標準出力に圧縮解除前のXMLを書き込む
  • フィルタリングなし


出力シンク

--output=stdout パイプのために圧縮されていないXMLもしくはSQL出力をstdoutに送る。

(文字集合の問題があるかもしれません。) output が指定されていない場合これは既定値です。

--output=file:<filename.xml> 圧縮されていない出力をファイルに書き込む。
--output=gzip:<filename.xml.gz> 圧縮されている出力をファイルに書き込む。
--output=bzip2:<filename.xml.bz2> 圧縮されている出力をファイルに書き込む。
--output=mysql:<jdbc url> SQL 形式の出力のみ有効になります; MySQL サーバーへの接続を開き、コマンドを直接送ります。

これは以下のようになります:
mysql://localhost/databasename?user=<username>&password=<password>

出力形式

  --format=xml
      MediaWiki の XML 書き出しファイル形式に戻して出力します; 制限された取り込みのためのフィルタリング ダンプに対して使用します。出力は冪等 (idempotent) です。
  --format=sql:1.4
      MediaWiki 1.4 のスキーマへのバルク インポートのための整形された SQL 文。
  --format=sql:1.5
      MediaWiki 1.5 のスキーマへのバルク インポートのために整形された SQL 文。
      両方の SQL スキーマ バージョンは現在テーブル構造が既に空のデータベースにセットアップされていることが必要です; MediaWiki ディストリビューションから maintenance/tables.sql を使用します。
  --format=sql:1.25
     SQL statements formatted for bulk import in MediaWiki 1.25's schema.

フィルター操作

  --filter=latest
      Skips all but the last revision listed for each page.
      FIXME: currently this pays no attention to the timestamp or
      revision number, but simply the order of items in the dump.
      This may or may not be strictly correct.
  --filter=list:<list-filename>
      Excludes all pages whose titles do not appear in the given file.
      Use one title per line; blanks and lines starting with # are
      ignored. Talk and subject pages of given titles are both matched.
  --filter=exactlist:<list-filename>
      As above, but does not try to match associated talk/subject pages.
  --filter=namespace:[!]<NS_KEY,NS_OTHERKEY,100,...>
      Includes only pages in (or not in, with "!") the given namespaces.
      You can use the NS_* constant names or the raw numeric keys.
  --filter=notalk
      Excludes all talk pages from output (including custom namespaces)
  --filter=titlematch:<regex>
      Excludes all pages whose titles do not match the regex.

その他のオプション

  --progress=<n>
      Change progress reporting interval from the default 1000 revisions.
  --quiet
      Don't send any progress output to stderr. Recommended when running under nohup.

Direct connection to MySQL

MySQLへの直接的な接続をしてmwdumperを使用する例

java -server -classpath mysql-connector-java-3.1.11/mysql-connector-java-3.1.11-bin.jar:mwdumper.jar \
   org.mediawiki.dumper.Dumper --output=mysql://127.0.0.1/testwiki?user=wiki\&password=wiki \
   --format=sql:1.25 20051020_pages_articles.xml.bz2
* You will need the mysql-connector JDBC driver. On Ubuntu this comes in package libmysql-java and is installed at /usr/share/java/mysql-connector-java.jar.
  • The JRE does not allow you to mix the -jar and -classpath arguments (hence the different command structure).
  • The --output argument must before the --format argument.
  • The ampersand in the MySQL URI must be escaped on Unix-like systems.


Windows XP上でMySQLに直接接続してmwdumperを使用する例

上記の例で問題を抱えました...次の例はXPでベターに動作します....

1.次のようなバッチファイルを作成する。

set class=mwdumper.jar;mysql-connector-java-3.1.12/mysql-connector-java-3.1.12-bin.jar
set data="C:\Documents and Settings\All Users.WINDOWS\Documents\en.wiki\enwiki-20060207-pages-articles.xml.bz2"
java -client -classpath %class% org.mediawiki.dumper.Dumper "--output=mysql://127.0.0.1/wikidb?user=<username>&password=<password>&characterEncoding=UTF8" "--format=sql:1.25" %data%
pause

2.mysql-connector-java-3.1.12-bin.jarとmwdumper.jarをダウンロードします

3.バッチ ファイルを実行します。

#It still reports a problem with the import files, "duplicate key"...
  1. The class path separator is a ; (semi-colon) in this example; different from the example above.

The "duplicate key" error may result from the page, revision and text tables in the database not being empty, or from character encoding problems. See A note on character encoding.

Performance Tips

Please elaborate on these tips if you can.

データベースへのインポートを速くするためには、以下を試してください:

Remove indexes and auto-increment fields

Temporarily remove all indexes and auto_increment fields from the following tables: page, revision and text. This gives a tremendous speed bump, because MySQL will otherwise be updating these indexes after each insert.

Don't forget to recreate the indexes afterwards.

  1. Remove indexes:
  2. Remove primary keys: In MySQL execute:
    • alter table revision drop primary key;
    • alter table text drop primary key;
    • alter table page drop primary key;
  3. Remove auto increment fields: In MySQL execute:
    • alter table revision change rev_id rev_id int(10) unsigned not null;
    • alter table text change old_id old_id int(10) unsigned not null;
    • alter table page change page_id page_id int(10) unsigned not null;
It will take a long time to recreate all the removed data.

Set -server option

Java's -server option may significantly increase performance on some versions of Sun's JVM for large files. (Not all installations will have this available.)

Increase MySQL's innodb_log_file_size

Increase MySQL's innodb_log_file_size in /etc/mysql/my.cnf. The default is as little as 5mb, but you can improve performance dramatically by increasing this to reduce the number of disk writes. innodb_log_file_size=64M is commonly a good log size; too large of a size may increase recovery time more than is desirable.

Shut down the server cleanly, and move away (don't delete) the log files, which are in /var/lib/mysql and named ib_logfile0, ib_logfile1, and so on. Change the innodb_log_file_size setting. Then restart the server. Test to see if the server is working; if all is well, you can delete the log files you moved.

Disable the binary log

If you don't need it, disable the binary log (log-bin option) during the import. On a standalone machine this is just wasteful, writing a second copy of every query that you'll never use.

To test if binary log is enabled via SQL command, issue the following statement:

SHOW VARIABLES LIKE 'log_bin';

More tips in the MySQL reference manual

Various other wacky tips can be found in the MySQL reference manual. If you find any useful ones, please write about them here.

Troubleshooting

If mwdumper gives java.lang.IllegalArgumentException: Invalid contributor exception, see タスク T20328.

If it gives java.lang.OutOfMemoryError: Java heap space exception, run it with larger heap size, for example java -Xms128m -Xmx1000m -jar mwdumper.jar ... (first is starting, second maximum size) (タスク T23937)

If an error is thrown with a reference to page_counter being missing, use the --format=sql:1.25 parameter. Alternatively, you can create a page_counter column on the page table.

Importing XML dumps from old MediaWiki versions may give errors of "Column 'rev_sha1' cannot be null". You'll need to change the column to accept null values, and run populateRevisionSha1.php afterwards.

How to build MWDumper from source

You can build MWDumper from source and let Maven sort out the dependencies. Just:

git clone https://phabricator.wikimedia.org/diffusion/MWDU/mwdumper.git
cd mwdumper
mvn compile
mvn package

It should generate the mwdumper<version number>.jar file (for example mwdumper-1.25.jar) on the folder named target.

Note that usage examples on this page use class=mwdumper.jar, so you should either rename the file to mwdumper.jar, or use class=mwdumper-1.25.jar instead.

Programming


Reporting bugs

Bugs can be reported in the Wikimedia bug tracker.

Change history (abbreviated)

  • 2016-04-23: Updated Xerces library to fix intermittent UTF-8 breakage
  • ... various bug fixes ...
  • ... build system changed to Maven ...
  • ... various bug fixes ...
  • 2005-10-25: Switched SqlWriter.sqlEscape back to less memory-hungry StringBuffer
  • 2005-10-24: Fixed SQL output in non-UTF-8 locales
  • 2005-10-21: Applied more speedup patches from Folke
  • 2005-10-11: SQL direct connection, GUI work begins
  • 2005-10-10: Applied speedup patches from Folke Behrens
  • 2005-10-05: Use bulk inserts in SQL mode
  • 2005-09-29: Converted from C# to Java
  • 2005-08-27: Initial extraction code

Todo

  • Add some more junit tests
  • Include table initialization in SQL output
  • Allow use of table prefixes in SQL output
  • Ensure that titles and other bits are validated correctly.
  • Test XML input for robustness
  • Provide filter to strip ID numbers
  • <siteinfo> is technically optional; live without it and use default namespaces
  • GUI frontend(s)
  • Port to Python? ;)

Alternate method of loading a huge wiki

MediaWiki バージョン:
1.32
Warning: This method takes days to run.

If you have to load a huge wiki this might help...

Below is a set of instructions that makes loading a large wiki less error prone and maybe a bit faster. It is not a script but rather a set of commands you can copy into bash (running in a screen session.) You'll have to babysit and customize the process for your needs.

警告 警告: Those commands drop several indices and then re-adds them again after the import. However, the index definition is from a specific MediaWiki version, which may not match your current version of MediaWiki. Use this method if you know what are you doing, and check if index definitions are correct.
# Dump SQL to disk in even sized chunks.  This takes about 80 Gb of hard drive space and 3 hours for enwiki.
# Setup the db to receive the chunks.  This takes a few seconds.
# Import the chunks.  This takes a few days for enwiki.
# Rebuild the DB.  This takes another day for enwiki.
# Run standard post import cleanup.  I haven't finished this step successfully yet but some of it can be skipped I think.

export DUMP_PREFIX=/public/datasets/public/enwiki/20130604/enwiki-20130604
export DIR_ROOT=/data/project/dump
export DIR=${DIR_ROOT}/enwiki
export EXPORT_PROCESSES=4
export IMPORT_PROCESSES=4
export DB=enwiki2
export EXPORT_FILE_SIZE=5
export EXPORT_FILE_SUFFIX_LENGTH=8
export LOG=~/log

bash -c 'sleep 1 && echo y' | mysqladmin drop ${DB} -u root
sudo rm -rf ${DIR}
rm -rf ${LOG}

sudo mkdir -p ${DIR}
sudo chown -R ${USER} ${DIR_ROOT}
mkdir -p ${LOG}

# Dump SQL to disk in even sized chunks.
# Sort by size descending to keep as many threads as possible hopping.
# uconv cleans up UTF-8 errors in the source files.
# grep removes BEGIN and COMMIT statements that mwdumper thinks are good, but I do better below
sudo apt-get install openjdk-7-jdk libicu-dev -y #jdk for mwdumper and libicu-dev for uconv
ls -1S ${DUMP_PREFIX}-pages-meta-current*.xml-p* |
  xargs -I{} -P${EXPORT_PROCESSES} -t bash -c '
  mkdir -p ${DIR}/$(basename {})
  cd ${DIR}/$(basename {})
  bunzip2 -c {} |
    uconv -f UTF-8 -t ascii --callback escape-xml-dec -v 2> ${LOG}/$(basename {}).uconv |
    java -jar ~/mwdumper-1.16.jar --format=sql:1.25 2> ${LOG}/$(basename {}).mwdumper |
    grep INSERT |
    split -l ${EXPORT_FILE_SIZE} -a ${EXPORT_FILE_SUFFIX_LENGTH} 2> ${LOG}/$(basename {}).split
  '

# Setup the db to receive the chunks.
mysqladmin create ${DB} --default-character-set=utf8 -u root
mysql -u root ${DB} < /srv/mediawiki/maintenance/tables.sql
mysql -u root ${DB} <<HERE
ALTER TABLE page
  CHANGE page_id page_id INTEGER UNSIGNED,
  DROP INDEX name_title,
  DROP INDEX page_random,
  DROP INDEX page_len,
  DROP INDEX page_redirect_namespace_len;
ALTER TABLE revision 
  CHANGE rev_id rev_id INTEGER UNSIGNED,
  DROP INDEX rev_page_id,
  DROP INDEX rev_timestamp,
  DROP INDEX page_timestamp,
  DROP INDEX user_timestamp,
  DROP INDEX usertext_timestamp,
  DROP INDEX page_user_timestamp;
ALTER TABLE text
  CHANGE old_id old_id INTEGER UNSIGNED;
HERE

# Import the chunks
# Each chunk is wrapped in a transaction and if the import succeeds the chunk is removed from disk.
# This means you should be able to safely ctrl-c the process at any time and rerun this block and
# it'll pick up where it left off.  The worst case scenario is you'll get some chunk that was added
# but not deleted and you'll see mysql duplicate key errors.  Or something like that.  Anyway, if you
# are reading this you are a big boy and can figure out how clean up the database or remove the file.
echo 'BEGIN;' > ${DIR_ROOT}/BEGIN
echo 'COMMIT;' > ${DIR_ROOT}/COMMIT
find ${DIR} -type f |
  sort -R |
  xargs -I{} -P${IMPORT_PROCESSES} -t bash -c '
    cat ${DIR_ROOT}/BEGIN {} ${DIR_ROOT}/COMMIT | mysql -u root ${DB} &&
    rm {}'

# Rebuild the DB
mysql -u root ${DB} <<HERE
CREATE TABLE bad_page AS 
  SELECT page_namespace, page_title, COUNT(*) AS count
  FROM page GROUP BY page_namespace, page_title
  HAVING count > 1;
UPDATE page, bad_page
  SET page.page_title = CONCAT(page.page_title, page.page_id)
  WHERE page.page_namespace = bad_page.page_namespace AND page.page_title = bad_page.page_title;
DROP TABLE bad_page;
ALTER TABLE page
  CHANGE page_id page_id INTEGER UNSIGNED AUTO_INCREMENT,
  ADD UNIQUE INDEX name_title (page_namespace,page_title),
  ADD INDEX page_random (page_random),
  ADD INDEX page_len (page_len),
  ADD INDEX page_redirect_namespace_len (page_is_redirect, page_namespace, page_len);
ALTER TABLE revision 
  CHANGE rev_id rev_id INTEGER UNSIGNED AUTO_INCREMENT,
  ADD UNIQUE INDEX rev_page_id (rev_page, rev_id),
  ADD INDEX rev_timestamp (rev_timestamp),
  ADD INDEX page_timestamp (rev_page,rev_timestamp),
  ADD INDEX user_timestamp (rev_user,rev_timestamp),
  ADD INDEX usertext_timestamp (rev_user_text,rev_timestamp),
  ADD INDEX page_user_timestamp (rev_page,rev_user,rev_timestamp);
ALTER TABLE text
  CHANGE old_id old_id INTEGER UNSIGNED AUTO_INCREMENT;
HERE

# Run standard post import cleanup
cd /srv/mediawiki
php maintenance/update.php

Notes


See also