Esegui query di Data Explorer con l'API di Discourse

:bookmark: Questa guida spiega come utilizzare l’API di Discourse per creare, eseguire e gestire query con il plugin Data Explorer.

:person_raising_hand: Livello utente richiesto: Amministratore

Praticamente qualsiasi azione che può essere eseguita tramite l’interfaccia utente di Discourse può anche essere attivata con l’API di Discourse.

Questo documento fornisce una panoramica completa per l’utilizzo dell’API specificamente in combinazione con il plugin Data Explorer.

Per una panoramica generale su come trovare la richiesta API corretta per un’azione, vedere: Reverse engineer the Discourse API .

Esecuzione di una query Data Explorer

Per eseguire una query Data Explorer tramite l’API, effettuare una richiesta POST a /admin/plugins/explorer/queries/<query-id>/run. È possibile trovare l’ID della query visitandola tramite il proprio sito Discourse e controllando il parametro id nella barra degli indirizzi.

Di seguito è riportato un esempio di query con un ID di 20 che restituisce argomenti per visualizzazioni in una data specificata:

--[params]
-- date :viewed_at

SELECT
topic_id,
COUNT(1) AS views_for_date
FROM topic_views
WHERE viewed_at = :viewed_at
GROUP BY topic_id
ORDER BY views_for_date DESC

Questa query può essere eseguita da un terminale con:

curl -X POST "https://your-site-url/admin/plugins/explorer/queries/20/run" \
-H "Content-Type: multipart/form-data;" \
-H "Api-Key: <api-key>" \
-H "Api-Username: system" \
-F 'params={"viewed_at":"2019-06-10"}'

Si noti che sarà necessario sostituire <api-key> e <your-site-url> con la propria chiave API e dominio.

Gestione di set di dati di grandi dimensioni

Il plugin Data Explorer limita i risultati a 1000 righe per impostazione predefinita. Per eseguire la paginazione attraverso set di dati più grandi, è possibile utilizzare la query di esempio seguente:

--[params]
-- integer :limit = 100
-- integer :page = 0
SELECT * 
FROM generate_series(1, 10000)
OFFSET :page * :limit 
LIMIT :limit

Per recuperare i risultati pagina per pagina, incrementare il parametro page nella richiesta:

curl -X POST "https://your-site-url/admin/plugins/explorer/queries/27/run" \
-H "Content-Type: multipart/form-data;" \
-H "Api-Key: <api-key>" \
-H "Api-Username: system" \
-F 'params={"page":"0"}'

Interrompere quando result_count è zero.

Per ulteriori informazioni sulla gestione di set di dati di grandi dimensioni, vedere: Result Limits and Exporting Queries

Rimozione dei dati relations dai risultati

Quando le query di Data Explorer vengono eseguite tramite l’interfaccia utente, un oggetto relations viene aggiunto ai risultati. Questi dati vengono utilizzati per il rendering dell’utente nei risultati dell’interfaccia utente, ma è improbabile che siano necessari quando si eseguono query tramite l’API.

Per rimuovere tali dati dai risultati, aggiungere un parametro download=true alla richiesta:

curl -X POST "https://your-site-url/admin/plugins/explorer/queries/27/run" \
-H "Content-Type: multipart/form-data;" \
-H "Api-Key: <api-key>" \
-H "Api-Username: system" \
-F 'params={"page":"0"}' \
-F "download=true"

Autenticazione API

I dettagli sulla generazione di una chiave API per le richieste sono disponibili qui: Create and configure an API key .

Se la chiave API verrà utilizzata solo per eseguire query di Data Explorer, è possibile selezionare “Granular” dal menu a discesa Scope, quindi selezionare lo scope “run queries”.

FAQ

Esiste un endpoint API che posso utilizzare per ottenere l’elenco dei report e i numeri ID? Voglio creare un menu a discesa con l’elenco?

Sì, è possibile effettuare una richiesta GET autenticata a /admin/plugins/explorer/queries.json per ottenere un elenco di tutte le query sul sito.

È possibile creare query tramite l’API?

Sì. La documentazione su come farlo si trova su Create a Data Explorer query using the API

È possibile inviare parametri con la richiesta post?

Sì, includere i parametri SQL utilizzando l’opzione -F, come mostrato negli esempi.

L’esportazione CSV per le query è supportata dall’API?

Sebbene l’output JSON sia standard, è possibile convertire manualmente i risultati in CSV. L’esportazione CSV nativa non è più supportata.

Risorse aggiuntive

39 Mi Piace
Watching API
"DataExplorer::ValidationError: Missing parameter end_date of type string
Get total list of topics and their view counts from Discourse API
Best API for All First Posts in a Category
Category API request downloads all topics
Reports by Discourse
TimeStamp of Tag
How can I get the list of Discourse Topic IDs dynamically
Passing params to Data Explorer using API requires enclosing a value
Get Latest topic for Current user
Getting recently updated posts using the REST API
`DataExplorer::ValidationError: Missing parameter` when running Data Explorer queries with [params] via API
`DataExplorer::ValidationError: Missing parameter` when running Data Explorer queries with [params] via API
Backend data retrieve for analytics
Discourse-user-notes API
Admin dashboard report reference guide
How to query the topics_with_no_response.json API with filters
Use API to get topics for a period using js
Access Discourse database with n8n
Why getUserById doesn't return the user's email?
Grant a custom badge through the API
Is there an API endpoint for recently edited posts
How to query gamification score via the API?
1.5X cheers on specific TL's or groups
Page Publishing
Identifying users in multiple groups using AND rather than OR?
Validation error even when parameter passed while running data explorer API with Curl
How to change the response default_limit in data explorer?
How to change the response default_limit in data explorer?
Order/Filter searched topics by latest update to First Post
API Filter users by emails, including secondary emails
Ability to have granular scope for data explorer?
Daily, weekly, or total stats by user over a specified time range
Looking for help posting automating data explorer reports to my forum
How to get all topics from a specific category using offset/page param in the API query?
Discourse 有哪个接口能直接获取某个帖子的最后一条评论信息
想得到活跃的用户——通过api
API endpoint to create invite links has moved to /invites.json
How to get a password from database?
Can I send an external URL to the Discourse API for it to return topics linking to that URL?
How to fetch posts/topics by multiple usernames
Restrict moderator access to only the stats panel on the admin dashboard?
How to get all the deleted posts for a specific topic
Discourse forum traffic query data
Download a user's posting history via Discourse API?
Discourse Data Explorer Query Response to Slack
Filter topics in category containing file attachments
Discord Integration with Webhooks
Download result of queries into Google Spreadsheet
Who's online "API"?
Is there any endpoint that would provide a user's external account IDs from their Discourse ID?
API post request without an Accept header returns 406
Best way to get (via API) a list of users from a group, and their bios
Create a Data Explorer query using the API
How to get a full list of badges of all users
API rate limits

Questo commento sembra implicare che sia possibile eseguire l’esportazione CSV dall’API. È possibile? Sono solo curioso perché ho bisogno dei dati in formato CSV. Posso sempre ottenerli in formato JSON e convertirli in CSV, ma se esiste un modo integrato per ottenere il CSV sarebbe un po’ più facile.

È possibile eseguire una query ‘come creato o aggiornato negli ultimi 50 secondi’?

:robot: L’IA dice

-- [params]
-- int :seconds = 50

SELECT
    p.id AS post_id,
    p.created_at,
    p.updated_at,
    p.raw AS post_content,
    p.user_id,
    t.title AS topic_title,
    t.id AS topic_id
FROM posts p
INNER JOIN topics t ON t.id = p.topic_id
WHERE
    (EXTRACT(EPOCH FROM (NOW() - p.created_at)) <= :seconds
    OR EXTRACT(EPOCH FROM (NOW() - p.updated_at)) <= :seconds)
    AND p.deleted_at IS NULL
    AND t.deleted_at IS NULL
ORDER BY p.created_at DESC
LIMIT 50

Ho fatto un rapido test, sembra funzionare :slight_smile:

1 Mi Piace

Non vedo il “mi piace :heart:” che ho aggiunto a un post usando la tua query.

Penso che tu debba usare post_actions

--[params]
--string :timespan = 50 seconds

SELECT post_id,
       user_id,
       created_at,
       updated_at,
       deleted_at
FROM  post_actions
WHERE post_action_type_id=2 AND updated_at > NOW() - INTERVAL :timespan

Versione con risultati più belli

--[params]
--string :timespan = 50 seconds
--boolean :include_in_timespan_deleted = false

SELECT
  post_id,
  user_id,
  CASE
    WHEN EXTRACT(EPOCH FROM (NOW() - created_at)) < 60 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - created_at))), ' seconds ago')
    WHEN EXTRACT(EPOCH FROM (NOW() - created_at)) < 3600 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - created_at)) / 60), ' minutes ago')
    WHEN EXTRACT(EPOCH FROM (NOW() - created_at)) < 86400 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - created_at)) / 3600), ' hours ago')
    ELSE CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - created_at)) / 86400), ' days ago')
  END AS relative_created_at,
  CASE
    WHEN EXTRACT(EPOCH FROM (NOW() - updated_at)) < 60 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - updated_at))), ' seconds ago')
    WHEN EXTRACT(EPOCH FROM (NOW() - updated_at)) < 3600 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - updated_at)) / 60), ' minutes ago')
    WHEN EXTRACT(EPOCH FROM (NOW() - updated_at)) < 86400 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - updated_at)) / 3600), ' hours ago')
    ELSE CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - updated_at)) / 86400), ' days ago')
  END AS relative_updated_at,
  CASE
    WHEN deleted_at IS NULL THEN 'no'
    WHEN EXTRACT(EPOCH FROM (NOW() - deleted_at)) < 60 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - deleted_at))), ' seconds ago')
    WHEN EXTRACT(EPOCH FROM (NOW() - deleted_at)) < 3600 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - deleted_at)) / 60), ' minutes ago')
    WHEN EXTRACT(EPOCH FROM (NOW() - deleted_at)) < 86400 THEN CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - deleted_at)) / 3600), ' hours ago')
    ELSE CONCAT(ROUND(EXTRACT(EPOCH FROM (NOW() - deleted_at)) / 86400), ' days ago')
  END AS relative_deleted_at
FROM
  post_actions
WHERE
  post_action_type_id = 2
  AND updated_at > NOW() - INTERVAL :timespan
  AND (
    :include_in_timespan_deleted = false
    OR (deleted_at IS NOT NULL AND deleted_at > NOW() - INTERVAL :timespan)
  )

2 Mi Piace

Oooh ho letto male! Ho letto la frase come “È possibile fare una query come ‘creato o aggiornato negli ultimi 50 secondi’?\n\n(notare la posizione dell’apostrofo singolo)”

1 Mi Piace

Grazie a tutti,

Ho pubblicato qui perché ask.discourse mi ha indirizzato qui.
Sto cercando di capire se l’API fornisce questa funzionalità.

1 Mi Piace

Sì, certo.

Crei la query in data explorer, quindi esegui la query tramite l’API come descritto in questa guida.

Ho appena eseguito la query di Moin tramite l’API e ha restituito correttamente i risultati attesi.

4 Mi Piace

Mi stavo chiedendo anche io. JSON è l’unico modo per esportare dati tramite API o è supportato anche l’esportazione CSV per Data Explorer?

Grazie a tutti,

Mi scuso per la risposta tardiva, ero offline per un po’.

Quello che sto facendo attualmente è cercare tutti gli argomenti/post creati oggi e filtrare gli argomenti/post aggiornati prima del timestamp.

1 Mi Piace

Se non vuoi sporcarti le mani, puoi chiedere al bot su ask.discourse.com. Di solito è abbastanza accurato per quanto riguarda le query SQL relative a Discourse (ma non presumere che sia corretto, controlla il codice per esserne sicuro).

1 Mi Piace

L’intestazione Content-Type è corretta?
Negli strumenti per sviluppatori, quando si ispeziona una query di Data Explorer con parametri, l’intestazione Content-Type appare come:

Content-Type: application/x-www-form-urlencoded; charset=UTF-8

Tuttavia, il comando cURL corrente include:

-H "Content-Type: multipart/form-data;"


1 Mi Piace
  • multipart/form-data
  • application/x-www-form-urlencoded
  • application/json

sono tutti content-type validi che puoi utilizzare quando effettui una richiesta api.

1 Mi Piace

@blake
language python
library requests
Potresti fornire una query di esempio dell’API Data Explorer che includa tre parametri
fare riferimento a Topic che afferma che i parametri devono essere rigorosamente tra virgolette doppie

Certamente, ecco un esempio che utilizza Python:

import json
import requests

API_KEY      = "YOUR_API_KEY"
API_USERNAME = "system"
QUERY_ID     = 20
SITE_URL     = "https://your-site-url"

# tutti i valori devono essere stringhe
params = {
    "user_id":   "2",
    "viewed_at": "2019-06-10",
    "limit":     "5"
}

# Data Explorer si aspetta i parametri come stringa codificata in JSON
payload = {
    "params": json.dumps(params)
}

url = f"{SITE_URL}/admin/plugins/explorer/queries/{QUERY_ID}/run"
headers = {
    "Api-Key":       API_KEY,
    "Api-Username":  API_USERNAME,
    "Content-Type":  "application/json"
}

r = requests.post(url, headers=headers, json=payload)
r.raise_for_status()
print(r.json())
3 Mi Piace