1. 程式人生 > >elasticsearch-sql

elasticsearch-sql

0.簡介

ES查詢有點複雜(term match bool agg filter geo),所以現在就有外掛用SQL查ES。目前只支援查詢,不支援寫入

1.elasticsearch安裝sql外掛

github地址:https://github.com/NLPchina/elasticsearch-sql

# 安裝外掛 (elasticsearch 6.4.0)
./bin/elasticsearch-plugin install https://github.com/NLPchina/elasticsearch-sql/releases/download/6.4.0.0/elasticsearch-sql-6.4.0.0.zip

2.SQL使用(data索引是之前建立的)

# 獲取索引列表
POST /_xpack/sql?format=txt
{
    "query": "SHOW tables"
}

# 查詢data索引
POST /_xpack/sql?format=txt
{
    "query": "DESC data"
}

# 查詢data索引有哪些欄位 
POST /_xpack/sql?format=txt
{
    "query": "SHOW COLUMNS IN data"
}

# 查詢目前支援的函式
POST /_xpack/sql?format=txt
{
    "query": "SHOW FUNCTIONS"
}

# 查詢data索引下資料
POST /_xpack/sql?format=txt
{
    "query": "SELECT * FROM data"
}

# 有空自己去看看
官方文件:https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-syntax-select.html

3.java使用elasticsearch-sql

# 下載驅動
https://www.elastic.co/downloads/jdbc-client

4.測試(MMP 需要白金賬號 有空還是自己寫一套吧)

Test
public void test() throws Exception {

    String url = "jdbc:es://172.22.2.133:9200";

    Properties properties = new Properties();
    // MMP 需要白金賬號
    properties.put("user", "");
    properties.put("password", "");

    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setUrl(url);
    dataSource.setProperties(properties);

    Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement();
    ResultSet results = statement.executeQuery("SELECT name, age, address FROM data");
    while (results.next()) {
        String name = results.getString(results.findColumn("name"));
        String address = results.getString(results.findColumn("address"));
        String age = results.getString(results.findColumn("age"));

        System.out.println("name:" + name + " age:" + age + " address:{3}" + address);
    }
}

原始碼:https://gitee.com/jsjack_wang/springboot-demo dev-es-sql分支