【问题标题】:InfluxDB-Python: Unable to query by Tag valueInfluxDB-Python:无法按标签值查询
【发布时间】:2021-03-02 17:05:24
【问题描述】:

我在使用 python 查询 InfluxDB 时遇到问题。

我有以下简单的代码:

from influxdb import InfluxDBClient

client = InfluxDBClient(host='localhost', port=8086)



client.create_database('pyexample')

databases= client.get_list_database()

client.switch_database('pyexample')


json_body = [
    {
        "measurement": "brushEvents",
        "tags": {
            "user": "1",
            "brushId": "6c89f539-71c6-490d-a28d-6c5d84c0ee2f"
        },
        "time": "2018-03-28T8:01:00Z",
        "fields": {
            "duration": 127
        },
        "measurement": "brushEvents",
        "tags": {
            "user": "Carol",
            "brushId": "6c89f539-71c6-490d-a28d-6c5d84c0ee2r"
        },
        "time": "2018-03-28T8:01:00Z",
        "fields": {
            "duration": 129
        },
        "measurement": "brushEvents",
        "tags": {
            "user": "Evi",
            "brushId": "6c89f539-71c6-490d-a28d-6c5d84c0ee2e"
        },
        "time": "2018-03-28T8:01:00Z",
        "fields": {
            "duration": 132
        }
    }
    
]
client.write_points(json_body)

query = client.query('SELECT * FROM "brushEvents" WHERE "user"="Carol" ')


print(query)

我试图只获取包含所有字段的用户 Carol,但使用上面的查询,我只收到一个空的 ResultSet({})。

我做错了什么?我什至用单引号尝试过。

提前感谢您的帮助!

【问题讨论】:

    标签: python influxdb influxdb-python


    【解决方案1】:

    您在代码中犯了两个错误:

    1. 您的 json 正文错误,您需要将每个度量值放在 {} 中并用 , 分隔它们,
    json_body = [
        {
            "measurement": "brushEvents",
            "tags": {
                "user": "1",
                "brushId": "6c89f539-71c6-490d-a28d-6c5d84c0ee2f"
            },
            "time": "2018-03-28T8:01:00Z",
            "fields": {
                "duration": 127
            }
        },
        {
            "measurement": "brushEvents",
            "tags": {
                "user": "Carol",
                "brushId": "6c89f539-71c6-490d-a28d-6c5d84c0ee2r"
            },
            "time": "2018-03-28T8:01:00Z",
            "fields": {
                "duration": 129
            }
        },
        {    
            "measurement": "brushEvents",
            "tags": {
                "user": "Evi",
                "brushId": "6c89f539-71c6-490d-a28d-6c5d84c0ee2e"
            },
            "time": "2018-03-28T8:01:00Z",
            "fields": {
                "duration": 132
            }
        }
    
    ]
    
    1. 您的标签值必须用单引号括起来:
    query = client.query('''SELECT * FROM "brushEvents" WHERE "user"='Carol' ''')
    

    另一种选择是使用参数绑定,这是首选方法:

    query = 'SELECT * FROM "brushEvents" WHERE user=$user'
    bind_params = {'user': 'Carol'}
    result = client.query(query, bind_params=bind_params)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-20
      • 2018-08-25
      • 2021-02-11
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      相关资源
      最近更新 更多