package com.example.repurchase.transport;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * 把sqlserver中LatLng的的数据导入到elasticsearch中
 */
@Component
public class TransportAnjukeDataToEs {
    @Resource(name = "sqlServerConnection")
    private Connection sqlServerConnection;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public void transportAnjukeDataToEs() throws SQLException, IOException {
        Statement sqlServerStatement = sqlServerConnection.createStatement();
        ResultSet sqlServerResultSet = sqlServerStatement.executeQuery("select * from LatLng where Lat != '0' and  Lng != '0'");
        Integer step = 1000;
        Integer num = 0;
        BulkRequest bulkRequest = new BulkRequest();
        while (sqlServerResultSet.next()) {
            num += 1;
            bulkRequest.add(new IndexRequest("anjuke_data").id(sqlServerResultSet.getString("MainId"))
                    .source(jsonBuilder()
                            .startObject()
                            .field("City", sqlServerResultSet.getString("City"))
                            .field("Community", sqlServerResultSet.getString("Community"))
                            .field("Address", sqlServerResultSet.getString("Address"))
                            .field("HousePrice", sqlServerResultSet.getString("HousePrice"))
                            .field("Unit", sqlServerResultSet.getString("Unit"))
                            .field("MainId", sqlServerResultSet.getString("MainId"))
                            .field("Location", sqlServerResultSet.getString("Lat") + "," + sqlServerResultSet.getString("Lng"))
                            .endObject()
                    )
            );
            if (num % step == 0) {
                restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
                System.out.println("插入了： " + num + " 条数据");
                bulkRequest = new BulkRequest();
            }
        }
        if (num % step != 0) {
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println("总共插入了： " + num + " 条数据");
        }
        sqlServerResultSet.close();
        sqlServerStatement.close();

    }
}
