Discourse Data Explorer

:discourse2: Summary Discourse Data Explorer allows you to make SQL queries against your live database, allowing for up-to-the-minute stats reporting.
:open_book: Install Guide This plugin is bundled with Discourse core. There is no need to install the plugin separately.

:information_source: If you’re looking for examples or support for any custom queries, you can find lots of topics in our Data & reporting category under the sql-query tag. If there’s not one to suit your particular needs, please feel free to create a new topic to ask the community for some help. :memo: Query Help

:discourse2: Hosted by us? This plugin is available on our Business and Enterprise plans. Data Explorer | Discourse - Civilized Discussion

After installing the plugin, head to /admin/plugins .

de1

Click on the “Settings” button, and turn on data explorer enabled, then return and reload the page.
There should now be a tab in the stacked nav called “ Data Explorer ”. Select it or head to /admin/plugins/explorer , then use the + , Import or Run buttons to get started.

Default queries

On a fresh install, the data explorer now ships with several queries that can help you draw insights from your forum’s activity. Open any query and click Run to try it out.

Here's what the stock queries look like.

Note: Default queries are picked up from this file: discourse-data-explorer/lib/discourse_data_explorer/queries.rb at main · discourse/discourse-data-explorer · GitHub

If you have an awesome query that you want everyone to have, make a PR just like this one.

Default queries cannot be edited, feel free to copy the sql and paste it into a new query if you’d like to modify them.

Writing queries

When you click any of the Edit buttons on a query view, or start a new Explorer Query, you are presented with a screen like the one below:

The top two boxes are the name and description of the query. The name is what you’re selecting in the dropdown box, and the description should be used for things like explaining what to put in the query parameters or to describe what data is being queried.

The left pane is where you write the SQL query. Minor syntax highlighting and checking is provided.

Automatically running queries

While you can always run a query by clicking the Run button, you can save time when loading a query by adding the run parameter to the URL.

For example: /admin/plugins/explorer/queries/123?run

When this parameter is added to the URL, the query will run as soon as you load the page, so you don’t need to click the Run button to see the results. This is especially helpful for queries you run frequently, allowing you to bookmark them or add them to your sidebar with the run parameter included for a one-click report.

Importing queries

For an example, let’s import one that I wrote. Download this file, then open the import dialog and select the file to be uploaded or paste the query in the text box. Click Import to save it and then click Run to see the results.

most-common-likers.dcquery (1).json (442 Bytes)

Looks like all of the Discourse developers like each other quite a bit :heart:

Searching for queries

If you’ve accumulated too many awesome queries, no problem! The search bar can help you filter through titles and descriptions.

Allow non-staff groups to run queries

You can add specific groups (including moderators) to a query to grant them access to it:

After saving, you can find it from the Groups page for that particular group on the Reports tab:

Click any query to open it and then the Run button to see the results. You can also bookmark group reports by clicking the Bookmark button.

Sharing queries with predefined parameters

If you have included user-defined parameters in your query, you can share a link to the query and include the parameters in the URL so they will be pre-filled when the page loads.

You must include parameters in the URL in this format params={"parameter_name":"value"}. Separate multiple parameters with commas. For example:

discourse.example.com/g/my-group/reports/6?params={"param1":"value1","param2":"value2"}

Couple with the run parameter mentioned above, you can share a report with predefined parameters that runs automatically when loaded.

Result limits and exporting queries

With large queries, you may notice that there is a limit on the number of rows that the Data Explorer will display. By default, the limit is set to 1000 rows. This is to prevent excessively large queries from slowing down or disrupting the performance of your Discourse instance.

If you want to bypass this limit, you have a few of options:

  1. Pagination: You can paginate your results. Instead of trying to return all results at once, you can write your query to return a specific range of results. You can then adjust this range to view different sections of your data. This won’t increase the limit, but it will allow you to view all your data in sections.
  2. Increase the limit: If you have access to the Discourse server and are comfortable making changes to Discourse settings, you can increase the limit. However, this should be done with caution. Increasing the limit can put a lot of load on your server if you’re not careful, especially if multiple users are running large queries at the same time.
  3. Download the Results: You also have the option to download the query results instead of viewing them directly in Discourse by clicking either the JSON or CSV button after running the query. Data downloaded from a query in JSON or CSV format will have a much higher results limit of 10,000 rows. For programmatic purposes, you want want to opt for the Json format, or if you’d like to work on the data in a spreadsheet application, the CSV format might be more convenient.

It’s generally a good idea to try and write more efficient queries, or to filter your data so that you’re only retrieving what you need, rather than trying to bypass the limit.

You can also export the SQL query itself in .JSON format by clicking the Export button. Queries that are exported using this method can then be imported into other Discourse sites, or used with third party applications.

Query plan

The “Include query plan” checkbox can be used for better understanding and optimizing your SQL queries.

When you check this box and run a query, Discourse will display the sequence of operations used to access data in the Discourse database. This can include operations like scans, joins, sorts, and other database actions. By examining the query plan, you can see exactly how the database is executing your query.

The Data Explorer tutorial series

We also have a dedicated sql-tutorial series about the Data Explorer! If you’re interested in learning more about writing SQL queries in Discourse, we highly recommend reading through the topics in this series:

Last edited by @hugh 2025-09-03T00:45:12Z

Last checked by @hugh 2025-09-03T00:45:21Z

Check documentPerform check on document:
119 Me gusta

¡Hola! :slight_smile:

Así que pregunté en este hilo cómo copiar los enlaces a todos los temas en una consulta de búsqueda. Me dirigieron aquí. Entonces, le pregunté al administrador de nuestro foro si teníamos este plugin instalado, lo cual tenemos. Sin embargo, no sabemos cómo usarlo para copiar todos los enlaces de una consulta de búsqueda a un archivo CSV usando este plugin. ¿Alguien ha realizado esta acción antes y quizás podría indicarnos la dirección correcta? :sweat_smile:

Tenga en cuenta que soy un usuario habitual del foro, no tengo poderes de personal. Sin embargo, estoy transmitiendo esta información al administrador del sitio, que sí los tiene y puede hacerlo por mí. :slight_smile:

¡Gracias de antemano!

¡Hola Preston!

El plugin Data Explorer te permite crear consultas SQL.

Quieres crear una nueva que liste los temas que buscas.

Luego, cuando ejecutes la consulta, verás un botón CSV para exportar el resultado a un archivo CSV.

¡Espero que eso ayude!

¡Avísanos si necesitas ayuda adicional para crear la consulta!

3 Me gusta

¡Gracias! Se lo haré saber :hugs:

3 publicaciones se dividieron en un nuevo tema: ¿Cómo evitar el límite de 10.000 resultados del explorador de datos?

Hola, tengo una solicitud de funcionalidad para este gran plugin.

Algunos de los informes que creo usando el Explorador de Datos, serían de gran ayuda para mi equipo si pudiera listarlos en la página de Informes del Panel (/admin/reports).

¿Sería posible añadir una opción a cada consulta del Explorador de Datos para que se liste en la página de Informes? Gracias.

Por ejemplo:

  • Listar esta consulta personalizada en la página de Informes
3 Me gusta

¡Gracias por esta función!

Estoy explorando cómo podríamos escribir métricas personalizadas. Estamos utilizando Discourse junto con Workadvent.re (una herramienta de colaboración 2D basada en avatares A/V).
Estoy ejecutando un script personalizado allí para registrar actividades en una hoja de Google a través de un webhook. Para tener todo centralizado en nuestra herramienta principal (Discourse), sería genial tener estos datos impresos en Discourse…
¿Algún consejo?

1 me gusta

Realmente esperaba que hubiera un generador de consultas que ayudara a escribir SQL. Mi SQL está viejo y oxidado, y escribirlo a mano es propenso a errores y consume mucho tiempo. ¡Sería bueno si hubiera una manera más fácil!

2 Me gusta

Hola @davidgs, bienvenido a Meta :wave: :slight_smile:

¿Has intentado usar un LLM como ChatGPT? Tiene una comprensión razonable de Discourse y ha sido bastante confiable cuando también necesité hacer consultas de exploración de datos.

A menudo escribo mis indicaciones como “Escribe una consulta de explorador de datos de Discourse que devuelva x,y,z de a,b,c donde…” y termino con algo bastante razonable.

En la parte superior derecha de esta página, también podrías ver un pequeño icono de robot como el de abajo.
image

Si ese es el caso, también podrías probar el Bot Ayudante de IA que está integrado con Meta.

2 Me gusta

La mayoría de nosotros no lo vemos. Pero siempre está ask.discourse.com

2 Me gusta

Sí, no recordaba si esto seguía siendo solo una cosa de nivel de confianza 3 o no. Buena idea con el sitio ask.discourse.com.

Como ejemplo de referencia, introduje escribe una consulta de explorador de datos de Discourse que devuelva una lista de todos los usuarios que dijeron la palabra “software” en la barra de entrada de texto de ask.discourse.com y obtuve la siguiente consulta:

SELECT 
    p.user_id, 
    u.username,
    COUNT(p.id) AS post_count
FROM 
    posts p
JOIN 
    users u ON u.id = p.user_id
WHERE 
    p.raw ILIKE '%software%'
GROUP BY 
    p.user_id, u.username
ORDER BY 
    post_count DESC;

Bastante razonable. También puedo dar fe de que hace consultas significativamente más complejas que esta.

2 Me gusta

La exportación de datos del explorador de datos ya no funciona con las últimas actualizaciones de Discourse y Data Explorer que instalé hace aproximadamente dos horas. Los datos se crean correctamente, pero ya no se pueden exportar.

Al hacer clic en los botones JSON o CSV, solo se produce un breve destello y no sucede nada más. Funcionaba bien hace unas dos semanas.

En la consola del navegador web, veo el siguiente error:
CSV:

Uncaught TypeError: this.args.query is undefined
    _downloadResult query-result.js:310
    downloadResultCsv query-result.js:287
    _triggerAction d-button.gjs:160
    Ember 12
    _triggerAction d-button.gjs:157
    click d-button.gjs:106

JSON:

Uncaught TypeError: this.args.query is undefined
    _downloadResult query-result.js:310
    downloadResultJson query-result.js:283
    _triggerAction d-button.gjs:160
    Ember 12
    _triggerAction d-button.gjs:157
    click d-button.gjs:106
1 me gusta

¡Gracias por el informe de error, @GuidoD!

Fusioné una corrección para este problema hoy temprano, por favor intenta actualizar y confirma que funciona para ti. :slight_smile:

2 Me gusta

gracias por la rápida solución.
Confirmo que vuelve a funcionar correctamente.

1 me gusta

Para una pequeña cantidad de datos, la exportación a JSON y CSV funciona bien. Pero para una mayor cantidad de datos, la exportación CSV funciona bien, pero la exportación JSON genera un error 502 Bad Gateway en nginx (probablemente debido a un tiempo de espera de 30 segundos, ya que la creación del archivo JSON tarda más de 30 segundos).
¿Hay alguna forma sencilla de aumentar el valor del tiempo de espera de nginx?

Si reduzco el período de tiempo de la consulta, el archivo CSV es de 12,9 MB y el archivo JSON es de 645 MB. El archivo CSV total es de 13,5 MB, por lo que es solo un poco más grande, pero el archivo JSON no se crea debido al error de nginx.

¿O tal vez la creación del archivo JSON está fallando debido a algunos datos extraños? ¿La creación del archivo JSON genera un archivo de registro?

Las consultas JSON se ejecutan con un LIMIT externo superior por defecto en comparación con las consultas CSV. Agregue paginación personalizada dentro de la consulta para asegurar que se complete a tiempo.

1 me gusta

¿Es posible ejecutar sentencias UPDATE desde el Explorador de datos?

Estoy intentando realizar una actualización masiva de una tabla determinada, pero obtengo este error:

PG::FeatureNotSupported: ERROR:  WITH query "query" does not have a RETURNING clause
LINE 29:   ) SELECT * FROM query

No, Data Explorer solo ejecuta transacciones de solo lectura. (Si actualizaste tu consulta para tener una cláusula RETURNING, obtendrías un error de transacción de solo lectura).

Si te alojas tú mismo, utiliza una de las guías de “launcher enter”, como

Si ya tienes tu UPDATE diseñado, entonces puedes usar psql discourse en lugar de rails c.

Si estás en un servicio alojado, ponte en contacto con el soporte para que ejecuten el cambio.

1 me gusta

Gracias por la respuesta. Tiene sentido. Estamos en un servicio alojado, así que me pondré en contacto con su soporte entonces.

Si comparto una consulta SQL con el grupo de moderadores, ¿cómo pueden los usuarios del grupo de moderadores ejecutar la consulta desde su cuenta? No pueden ver el plugin Explorador de datos.