文档

使用Python SDK管理索引

更新时间:

索引是一种倒排的数据存储结构,由关键词和指向实际数据的逻辑指针组成,用于快速根据关键词定位到具体数据行,类似于数据的目录。您只有配置索引后,才能进行查询和分析操作。本文通过代码示例介绍如何创建、修改、查询、删除索引。

前提条件

  • 已创建RAM用户并完成授权。具体操作,请参见创建RAM用户并完成授权

  • 已配置环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET。具体操作,请参见配置环境变量

    重要
    • 阿里云账号的AccessKey拥有所有API的访问权限,建议您使用RAM用户的AccessKey进行API访问或日常运维。

    • 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。

  • 已安装Python SDK。更多信息,请参见安装Python SDK

  • 已写入日志到Logstore。具体操作,请参见数据采集概述

注意事项

本示例以华东1(杭州)的公网Endpoint为例,其公网Endpoint为https://cn-hangzhou.log.aliyuncs.com。如果您通过与Project同地域的其他阿里云产品访问日志服务,请使用内网Endpointhttps://cn-hangzhou-intranet.log.aliyuncs.com。关于日志服务支持的地域与Endpoint的对应关系,请参见服务入口

原始日志样例

body_bytes_sent:1750
host:www.example.com
http_referer:www.example.com
http_user_agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; it-it) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27
http_x_forwarded_for:203.0.XX.XX
remote_addr:203.0.XX.XX
remote_user:p288
request_length:13741
request_method:GET
request_time:71
request_uri:/request/path-1/file-1
http_code:200
time_local:11/Aug/2021:06:52:27
upstream_response_time:0.66

创建索引示例代码

控制台界面支持界面化配置索引,操作更便捷。具体操作,请参见创建索引

以下代码用于创建索引。该示例中,基于原始日志样例,开启全文索引,为request_method、status字段开启字段索引。

索引配置
from aliyun.log import LogClient, IndexConfig
import os

# 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。
endpoint = "cn-hangzhou.log.aliyuncs.com"
# 创建日志服务Client。
client = LogClient(endpoint, accessKeyId, accessKey)

# Project名称。
project_name = "ali-test-project"
# Logstore名称。
logstore_name = "ali-test-logstore"


if __name__ == '__main__':
    # 创建索引前,必须规划好全文索引、字段索引配置。该示例中,开启全文索引,为request_method、status字段开启字段索引。
    logstore_index = {'line': {
        'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n',
                  '\t',
                  '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'request_method': {'type': 'text',
                                                                                 'token': [',', ' ', "'", '"', ';', '=',
                                                                                           '(', ')', '[', ']', '{', '}',
                                                                                           '?', '@', '&', '<', '>', '/',
                                                                                           ':', '\n', '\t', '\r'],
                                                                                 'caseSensitive': False, 'alias': '',
                                                                                 'doc_value': True, 'chn': False},
                                                                         'status': {'type': 'long', 'alias': '',
                                                                                'doc_value': True}},
        'log_reduce': False,
        'max_text_len': 2048}

    print("ready to create index")
    index_config = IndexConfig()
    index_config.from_json(logstore_index)
    client.create_index(project_name, logstore_name, index_config)
    print("create index success ")

预期结果如下:

ready to create index
create index success

更新索引示例代码

控制台界面支持界面化配置索引,操作更便捷。具体操作,请参见创建索引

以下代码用于更新索引。该示例中,基于原始日志样例,开启全文索引,为request_method、status开启字段索引,并设置request_method字段大小写敏感为True。

更新索引
from aliyun.log import LogClient, IndexConfig
import os

# 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。
endpoint = "cn-hangzhou.log.aliyuncs.com"
# 创建日志服务Client。
client = LogClient(endpoint, accessKeyId, accessKey)

# Project名称。
project_name = "ali-test-project"
# Logstore名称。
logstore_name = "ali-test-logstore"


if __name__ == '__main__':
    # 设置request_method字段大小写敏感为True。
    logstore_index = {'line': {
        'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n',
                  '\t',
                  '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'request_method': {'type': 'text',
                                                                                 'token': [',', ' ', "'", '"', ';', '=',
                                                                                           '(', ')', '[', ']', '{', '}',
                                                                                           '?', '@', '&', '<', '>', '/',
                                                                                           ':', '\n', '\t', '\r'],
                                                                                 'caseSensitive': True, 'alias': '',
                                                                                 'doc_value': True, 'chn': False},
                                                                         'status': {'type': 'long', 'alias': '',
                                                                                'doc_value': True}},
        'log_reduce': False,
        'max_text_len': 2048}

    print("ready to update index")
    index_config = IndexConfig()
    index_config.from_json(logstore_index)
    client.update_index(project_name, logstore_name, index_config)
    print("update index success ")

预期结果如下:

ready to update index
update index success

查询索引示例代码

以下代码用于查询指定Logstore的索引信息。

from aliyun.log import LogClient, IndexConfig
import os

# 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。
endpoint = "cn-hangzhou.log.aliyuncs.com"
# 创建日志服务Client。
client = LogClient(endpoint, accessKeyId, accessKey)

# Project名称。
project_name = "ali-test-project"
# Logstore名称。
logstore_name = "ali-test-logstore"


if __name__ == '__main__':
    # 查询索引。
    print("ready to list index")
    res = client.get_index_config(project_name, logstore_name)
    print("The index config is :%s" % res.get_index_config().to_json())
    print("list index success ")

预期结果如下:

ready to list index
The index config is :{'line': {'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n', '\t', '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'request_method': {'type': 'text', 'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n', '\t', '\r'], 'caseSensitive': True, 'alias': '', 'doc_value': True, 'chn': False}, 'status': {'type': 'long', 'alias': '', 'doc_value': True}}, 'log_reduce': False, 'max_text_len': 2048}
list index success

删除索引示例代码

以下代码用于删除指定Logstore的索引信息。

from aliyun.log import LogClient, IndexConfig
import os

# 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。
endpoint = "cn-hangzhou.log.aliyuncs.com"
# 创建日志服务Client。
client = LogClient(endpoint, accessKeyId, accessKey)

# Project名称。
project_name = "ali-test-project"
# Logstore名称。
logstore_name = "ali-test-logstore2"


if __name__ == '__main__':
    # 删除索引。
    print("ready to delete index")
    client.delete_index(project_name, logstore_name)
    print("delete index success ")

预期结果如下:

ready to delete index
delete index success

相关文档

  • 本页导读 (1)
文档反馈