Python接口_v2(推荐)

导入

把 esqlx.x.x/api/python/v2/esql_api.py 复制到项目所在目录, 并在需要调用esql的程序中导入

from esql_api import ESql

ESql接口类定义

class ESql(object):
    def __init__(self, host='127.0.0.1', port=8001, username=None, password=None):
    def login(self):
    def execute(self, sql):
    def file_set(file_path, params=None):
    def file_get(self, file_id):
    def logout(self):

创建ESQL实例

esql = ESql('esql_server_ip_address', 8001, 'username', 'password')

服务器开启免认证模式时,无需设置 username / password ,也无需登录(login):

esql = ESql('esql_server_ip_address', 8001)

登录

result = esql.login()
if result.state != 'Success':
    print(result)

执行SQL

result = esql.execute('show version;')

返回的数据字典(result).

登出

result = esql.logout()

file_set

设置文件字段 INSERT 时的 VALUES 值

params = {'_content_type': 'application/pdf'}
file_value = esql.file_set(file_path='/xxx/xxx/xxx.pdf', params=params)

INSERT INTO file_test(my_file()) values(%s); 语句中的 %s 用 file_value 的内容代入即可

  • params 参数可以不设置

  • params 参数没设置 _name 时, 会从file_path中自动识别(例子中为xxx.pdf)

  • params 参数可设置的值有:

    _name 文件名称
    _content_type 文件类型
    _language 语言种类

实际索引文件内容时,程序会根据文件内容自动识别文件类型,而不是通过_name中的扩展名 或 _content_type来判断

file_get

通过 file_id 获取文件内容, 例:

file_info = select_result['data'][0]['my_file']
result = esql.file_get(file_info['_file_id'])
if result['state'] == 'Success':
    file_obj = result['data'][0]
    file_content = file_obj.read()
    with open('/tmp/xxx.pdf', 'w') as out:
        out.write(file_content)
    print('%s    >    /tmp/sql_92_table.pdf' % file_info['_file_id'])

这里的 select_result 为select检索得到的结果集

完整的API调用样例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# -*- coding: utf-8 -*-
import os
import json

from esql_api import ESql


if __name__ == '__main__':

    # esql = ESql('10.68.23.81', 8001, 'root', 'toor')
    esql = ESql('127.0.0.1', 8001, 'root', 'toor')

    print(esql.login())

    print(esql.execute('drop table file_test;'))
    print(esql.execute("create table file_test(my_file FILE {analyzer=ik});"))

    test_file = os.path.realpath(os.path.join(__file__, '..',
                                              '..', '..', '..', 'websql', 'tests', 'data', 'es_guide_cn.pdf'))
    print(esql.execute("INSERT INTO file_test(my_file()) values(%s);" % esql.file_set(test_file)))
    print(esql.execute('flush file_test;'))

    # select_result = esql.execute("select * from file_test where my_file like 'analyser';")
    select_result = esql.execute("select * from file_test where my_file like '分析';")
    file_info = json.loads(select_result['data'][0]['my_file'])
    _ret = esql.file_get(file_info['_file_id'])
    with open('/tmp/es_guide_cn.pdf', 'w') as out:
        out.write(_ret['data'][0].read())
    print('%s    >    /tmp/es_guide_cn.pdf' % file_info['_file_id'])

    print(esql.logout())