Move clustering logic to metadata.

Close #1297.