`
rockelixir
  • 浏览: 310133 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
elasticsearch 批量索引 elasticsearch 批量索引
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

import java.io.IOException;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;

/**
 * 批量索引
 * 
 * @author xiaochuan.zhang
 * @version $Id: BulkMappingIndexer.java, v 0.1 2013-6-6 下午4:19:15 xiaochuan.zhang Exp $
 */
public class BulkMappingIndexer {

    public Client client;

    /**
     * 构造函数
     */
    public BulkMappingIndexer() {
        //使用本机做为节点
        this("127.0.0.1");
    }

    /**
     * 构造函数
     * 
     * @param ipAddress
     */
    public BulkMappingIndexer(String ipAddress) {
        /*如果10秒没有连接上搜索服务器,即超时*/
        Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "SusongES")
            .put("client.transport.ping_timeout", "10s").build();
        client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(
            ipAddress, 9300));
    }

    public Integer addBulkIndex(String indexName, String indexType) {
        BulkRequestBuilder bulkRequest = client.prepareBulk();
        long time = System.currentTimeMillis();
        for (int i = 0; i < 200; i++) {
            try {
                IndexRequestBuilder indexRequestBuilder = client.prepareIndex(indexName, indexType);
                XContentBuilder xContentBuilder = jsonBuilder().startObject().field("id", i)
                    .field("name", "中华人民共和国" + i).endObject();
                indexRequestBuilder.setSource(xContentBuilder);
                bulkRequest.add(indexRequestBuilder);
            } catch (IOException e) {
                System.out.println(e);
            }
        }
        bulkRequest.execute().actionGet();
        bulkRequest.setRefresh(true);
        System.out.println("索引耗时:" + (System.currentTimeMillis() - time) + "ms");
        return bulkRequest.numberOfActions();
    }

    /**
     * 执行索引
     * 
     * @param args
     */
    public static void main(String[] args) {
        BulkMappingIndexer bulkIndexer = new BulkMappingIndexer();
        bulkIndexer.addBulkIndex("index", "SS_ES");
    }
}
Global site tag (gtag.js) - Google Analytics