SQL-based ingestion API

SQL-based ingestion - 图1info

This page describes SQL-based batch ingestion using the druid-multi-stage-query extension, new in Druid 24.0. Refer to the ingestion methods table to determine which ingestion method is right for you.

The Query view in the web console provides a friendly experience for the multi-stage query task engine (MSQ task engine) and multi-stage query architecture. We recommend using the web console if you do not need a programmatic interface.

When using the API for the MSQ task engine, the action you want to take determines the endpoint you use:

  • /druid/v2/sql/task endpoint: Submit a query for ingestion.
  • /druid/indexer/v1/task endpoint: Interact with a query, including getting its status, getting its details, or canceling it. This page describes a few of the Overlord Task APIs that you can use with the MSQ task engine. For information about Druid APIs, see the API reference for Druid.

Submit a query

You submit queries to the MSQ task engine using the POST /druid/v2/sql/task/ endpoint.

Request

The SQL task endpoint accepts SQL requests in the JSON-over-HTTP form using the query, context, and parameters fields, but ignoring the resultFormat, header, typesHeader, and sqlTypesHeader fields.

This endpoint accepts INSERT and REPLACE statements.

As an experimental feature, this endpoint also accepts SELECT queries. SELECT query results are collected from workers by the controller, and written into the task report as an array of arrays. The behavior and result format of plain SELECT queries (without INSERT or REPLACE) is subject to change.

  • HTTP
  • curl
  • Python
  1. POST /druid/v2/sql/task
  1. {
  2. "query": "INSERT INTO wikipedia\nSELECT\n TIME_PARSE(\"timestamp\") AS __time,\n *\nFROM TABLE(\n EXTERN(\n '{\"type\": \"http\", \"uris\": [\"https://druid.apache.org/data/wikipedia.json.gz\"]}',\n '{\"type\": \"json\"}',\n '[{\"name\": \"added\", \"type\": \"long\"}, {\"name\": \"channel\", \"type\": \"string\"}, {\"name\": \"cityName\", \"type\": \"string\"}, {\"name\": \"comment\", \"type\": \"string\"}, {\"name\": \"commentLength\", \"type\": \"long\"}, {\"name\": \"countryIsoCode\", \"type\": \"string\"}, {\"name\": \"countryName\", \"type\": \"string\"}, {\"name\": \"deleted\", \"type\": \"long\"}, {\"name\": \"delta\", \"type\": \"long\"}, {\"name\": \"deltaBucket\", \"type\": \"string\"}, {\"name\": \"diffUrl\", \"type\": \"string\"}, {\"name\": \"flags\", \"type\": \"string\"}, {\"name\": \"isAnonymous\", \"type\": \"string\"}, {\"name\": \"isMinor\", \"type\": \"string\"}, {\"name\": \"isNew\", \"type\": \"string\"}, {\"name\": \"isRobot\", \"type\": \"string\"}, {\"name\": \"isUnpatrolled\", \"type\": \"string\"}, {\"name\": \"metroCode\", \"type\": \"string\"}, {\"name\": \"namespace\", \"type\": \"string\"}, {\"name\": \"page\", \"type\": \"string\"}, {\"name\": \"regionIsoCode\", \"type\": \"string\"}, {\"name\": \"regionName\", \"type\": \"string\"}, {\"name\": \"timestamp\", \"type\": \"string\"}, {\"name\": \"user\", \"type\": \"string\"}]'\n )\n)\nPARTITIONED BY DAY",
  3. "context": {
  4. "maxNumTasks": 3
  5. }
  6. }
  1. # Make sure you replace `username`, `password`, `your-instance`, and `port` with the values for your deployment.
  2. curl --location --request POST 'https://<username>:<password>@<your-instance>:<port>/druid/v2/sql/task/' \
  3. --header 'Content-Type: application/json' \
  4. --data-raw '{
  5. "query": "INSERT INTO wikipedia\nSELECT\n TIME_PARSE(\"timestamp\") AS __time,\n *\nFROM TABLE(\n EXTERN(\n '\''{\"type\": \"http\", \"uris\": [\"https://druid.apache.org/data/wikipedia.json.gz\"]}'\'',\n '\''{\"type\": \"json\"}'\'',\n '\''[{\"name\": \"added\", \"type\": \"long\"}, {\"name\": \"channel\", \"type\": \"string\"}, {\"name\": \"cityName\", \"type\": \"string\"}, {\"name\": \"comment\", \"type\": \"string\"}, {\"name\": \"commentLength\", \"type\": \"long\"}, {\"name\": \"countryIsoCode\", \"type\": \"string\"}, {\"name\": \"countryName\", \"type\": \"string\"}, {\"name\": \"deleted\", \"type\": \"long\"}, {\"name\": \"delta\", \"type\": \"long\"}, {\"name\": \"deltaBucket\", \"type\": \"string\"}, {\"name\": \"diffUrl\", \"type\": \"string\"}, {\"name\": \"flags\", \"type\": \"string\"}, {\"name\": \"isAnonymous\", \"type\": \"string\"}, {\"name\": \"isMinor\", \"type\": \"string\"}, {\"name\": \"isNew\", \"type\": \"string\"}, {\"name\": \"isRobot\", \"type\": \"string\"}, {\"name\": \"isUnpatrolled\", \"type\": \"string\"}, {\"name\": \"metroCode\", \"type\": \"string\"}, {\"name\": \"namespace\", \"type\": \"string\"}, {\"name\": \"page\", \"type\": \"string\"}, {\"name\": \"regionIsoCode\", \"type\": \"string\"}, {\"name\": \"regionName\", \"type\": \"string\"}, {\"name\": \"timestamp\", \"type\": \"string\"}, {\"name\": \"user\", \"type\": \"string\"}]'\''\n )\n)\nPARTITIONED BY DAY",
  6. "context": {
  7. "maxNumTasks": 3
  8. }
  9. }'
  1. import json
  2. import requests
  3. # Make sure you replace `your-instance`, and `port` with the values for your deployment.
  4. url = "https://<your-instance>:<port>/druid/v2/sql/task/"
  5. payload = json.dumps({
  6. "query": "INSERT INTO wikipedia\nSELECT\n TIME_PARSE(\"timestamp\") AS __time,\n *\nFROM TABLE(\n EXTERN(\n '{\"type\": \"http\", \"uris\": [\"https://druid.apache.org/data/wikipedia.json.gz\"]}',\n '{\"type\": \"json\"}',\n '[{\"name\": \"added\", \"type\": \"long\"}, {\"name\": \"channel\", \"type\": \"string\"}, {\"name\": \"cityName\", \"type\": \"string\"}, {\"name\": \"comment\", \"type\": \"string\"}, {\"name\": \"commentLength\", \"type\": \"long\"}, {\"name\": \"countryIsoCode\", \"type\": \"string\"}, {\"name\": \"countryName\", \"type\": \"string\"}, {\"name\": \"deleted\", \"type\": \"long\"}, {\"name\": \"delta\", \"type\": \"long\"}, {\"name\": \"deltaBucket\", \"type\": \"string\"}, {\"name\": \"diffUrl\", \"type\": \"string\"}, {\"name\": \"flags\", \"type\": \"string\"}, {\"name\": \"isAnonymous\", \"type\": \"string\"}, {\"name\": \"isMinor\", \"type\": \"string\"}, {\"name\": \"isNew\", \"type\": \"string\"}, {\"name\": \"isRobot\", \"type\": \"string\"}, {\"name\": \"isUnpatrolled\", \"type\": \"string\"}, {\"name\": \"metroCode\", \"type\": \"string\"}, {\"name\": \"namespace\", \"type\": \"string\"}, {\"name\": \"page\", \"type\": \"string\"}, {\"name\": \"regionIsoCode\", \"type\": \"string\"}, {\"name\": \"regionName\", \"type\": \"string\"}, {\"name\": \"timestamp\", \"type\": \"string\"}, {\"name\": \"user\", \"type\": \"string\"}]'\n )\n)\nPARTITIONED BY DAY",
  7. "context": {
  8. "maxNumTasks": 3
  9. }
  10. })
  11. headers = {
  12. 'Content-Type': 'application/json'
  13. }
  14. response = requests.post(url, headers=headers, data=payload, auth=('USER', 'PASSWORD'))
  15. print(response.text)

Response

  1. {
  2. "taskId": "query-f795a235-4dc7-4fef-abac-3ae3f9686b79",
  3. "state": "RUNNING",
  4. }

Response fields

FieldDescription
taskIdController task ID. You can use Druid’s standard Tasks API to interact with this controller task.
stateInitial state for the query, which is “RUNNING”.

Get the status for a query task

You can retrieve status of a query to see if it is still running, completed successfully, failed, or got canceled.

Request

  • HTTP
  • curl
  • Python
  1. GET /druid/indexer/v1/task/<taskId>/status
  1. # Make sure you replace `username`, `password`, `your-instance`, `port`, and `taskId` with the values for your deployment.
  2. curl --location --request GET 'https://<username>:<password>@<your-instance>:<port>/druid/indexer/v1/task/<taskId>/status'
  1. import requests
  2. # Make sure you replace `your-instance`, `port`, and `taskId` with the values for your deployment.
  3. url = "https://<your-instance>:<port>/druid/indexer/v1/task/<taskId>/status"
  4. payload={}
  5. headers = {}
  6. response = requests.get(url, headers=headers, data=payload, auth=('USER', 'PASSWORD'))
  7. print(response.text)

Response

  1. {
  2. "task": "query-3dc0c45d-34d7-4b15-86c9-cdb2d3ebfc4e",
  3. "status": {
  4. "id": "query-3dc0c45d-34d7-4b15-86c9-cdb2d3ebfc4e",
  5. "groupId": "query-3dc0c45d-34d7-4b15-86c9-cdb2d3ebfc4e",
  6. "type": "query_controller",
  7. "createdTime": "2022-09-14T22:12:00.183Z",
  8. "queueInsertionTime": "1970-01-01T00:00:00.000Z",
  9. "statusCode": "RUNNING",
  10. "status": "RUNNING",
  11. "runnerStatusCode": "RUNNING",
  12. "duration": -1,
  13. "location": {
  14. "host": "localhost",
  15. "port": 8100,
  16. "tlsPort": -1
  17. },
  18. "dataSource": "kttm_simple",
  19. "errorMsg": null
  20. }
  21. }

Get the report for a query task

A report provides detailed information about a query task, including things like the stages, warnings, and errors.

Keep the following in mind when using the task API to view reports:

  • The task report for an entire job is associated with the query_controller task. The query_worker tasks do not have their own reports; their information is incorporated into the controller report.
  • The task report API may report 404 Not Found temporarily while the task is in the process of starting up.
  • As an experimental feature, the MSQ task engine supports running SELECT queries. SELECT query results are written into the multiStageQuery.payload.results.results task report key as an array of arrays. The behavior and result format of plain SELECT queries (without INSERT or REPLACE) is subject to change.
  • multiStageQuery.payload.results.resultsTruncated denote whether the results of the report have been truncated to prevent the reports from blowing up

For an explanation of the fields in a report, see Report response fields.

Request

  • HTTP
  • curl
  • Python
  1. GET /druid/indexer/v1/task/<taskId>/reports
  1. # Make sure you replace `username`, `password`, `your-instance`, `port`, and `taskId` with the values for your deployment.
  2. curl --location --request GET 'https://<username>:<password>@<your-instance>:<port>/druid/indexer/v1/task/<taskId>/reports'
  1. import requests
  2. # Make sure you replace `your-instance`, `port`, and `taskId` with the values for your deployment.
  3. url = "https://<your-instance>:<port>/druid/indexer/v1/task/<taskId>/reports"
  4. headers = {}
  5. response = requests.get(url, headers=headers, auth=('USER', 'PASSWORD'))
  6. print(response.text)

Response

The response shows an example report for a query.

Show the response

  1. {
  2. "multiStageQuery": {
  3. "type": "multiStageQuery",
  4. "taskId": "query-3dc0c45d-34d7-4b15-86c9-cdb2d3ebfc4e",
  5. "payload": {
  6. "status": {
  7. "status": "SUCCESS",
  8. "startTime": "2022-09-14T22:12:09.266Z",
  9. "durationMs": 28227,
  10. "pendingTasks": 0,
  11. "runningTasks": 2
  12. },
  13. "stages": [
  14. {
  15. "stageNumber": 0,
  16. "definition": {
  17. "id": "71ecb11e-09d7-42f8-9225-1662c8e7e121_0",
  18. "input": [
  19. {
  20. "type": "external",
  21. "inputSource": {
  22. "type": "http",
  23. "uris": [
  24. "https://static.imply.io/example-data/kttm-v2/kttm-v2-2019-08-25.json.gz"
  25. ],
  26. "httpAuthenticationUsername": null,
  27. "httpAuthenticationPassword": null
  28. },
  29. "inputFormat": {
  30. "type": "json",
  31. "flattenSpec": null,
  32. "featureSpec": {},
  33. "keepNullColumns": false
  34. },
  35. "signature": [
  36. {
  37. "name": "timestamp",
  38. "type": "STRING"
  39. },
  40. {
  41. "name": "agent_category",
  42. "type": "STRING"
  43. },
  44. {
  45. "name": "agent_type",
  46. "type": "STRING"
  47. }
  48. ]
  49. }
  50. ],
  51. "processor": {
  52. "type": "scan",
  53. "query": {
  54. "queryType": "scan",
  55. "dataSource": {
  56. "type": "inputNumber",
  57. "inputNumber": 0
  58. },
  59. "intervals": {
  60. "type": "intervals",
  61. "intervals": [
  62. "-146136543-09-08T08:23:32.096Z/146140482-04-24T15:36:27.903Z"
  63. ]
  64. },
  65. "resultFormat": "compactedList",
  66. "columns": [
  67. "agent_category",
  68. "agent_type",
  69. "timestamp"
  70. ],
  71. "legacy": false,
  72. "context": {
  73. "finalize": false,
  74. "finalizeAggregations": false,
  75. "groupByEnableMultiValueUnnesting": false,
  76. "scanSignature": "[{\"name\":\"agent_category\",\"type\":\"STRING\"},{\"name\":\"agent_type\",\"type\":\"STRING\"},{\"name\":\"timestamp\",\"type\":\"STRING\"}]",
  77. "sqlInsertSegmentGranularity": "{\"type\":\"all\"}",
  78. "sqlQueryId": "3dc0c45d-34d7-4b15-86c9-cdb2d3ebfc4e",
  79. "sqlReplaceTimeChunks": "all"
  80. },
  81. "granularity": {
  82. "type": "all"
  83. }
  84. }
  85. },
  86. "signature": [
  87. {
  88. "name": "__boost",
  89. "type": "LONG"
  90. },
  91. {
  92. "name": "agent_category",
  93. "type": "STRING"
  94. },
  95. {
  96. "name": "agent_type",
  97. "type": "STRING"
  98. },
  99. {
  100. "name": "timestamp",
  101. "type": "STRING"
  102. }
  103. ],
  104. "shuffleSpec": {
  105. "type": "targetSize",
  106. "clusterBy": {
  107. "columns": [
  108. {
  109. "columnName": "__boost"
  110. }
  111. ]
  112. },
  113. "targetSize": 3000000
  114. },
  115. "maxWorkerCount": 1,
  116. "shuffleCheckHasMultipleValues": true
  117. },
  118. "phase": "FINISHED",
  119. "workerCount": 1,
  120. "partitionCount": 1,
  121. "startTime": "2022-09-14T22:12:11.663Z",
  122. "duration": 19965,
  123. "sort": true
  124. },
  125. {
  126. "stageNumber": 1,
  127. "definition": {
  128. "id": "71ecb11e-09d7-42f8-9225-1662c8e7e121_1",
  129. "input": [
  130. {
  131. "type": "stage",
  132. "stage": 0
  133. }
  134. ],
  135. "processor": {
  136. "type": "segmentGenerator",
  137. "dataSchema": {
  138. "dataSource": "kttm_simple",
  139. "timestampSpec": {
  140. "column": "__time",
  141. "format": "millis",
  142. "missingValue": null
  143. },
  144. "dimensionsSpec": {
  145. "dimensions": [
  146. {
  147. "type": "string",
  148. "name": "timestamp",
  149. "multiValueHandling": "SORTED_ARRAY",
  150. "createBitmapIndex": true
  151. },
  152. {
  153. "type": "string",
  154. "name": "agent_category",
  155. "multiValueHandling": "SORTED_ARRAY",
  156. "createBitmapIndex": true
  157. },
  158. {
  159. "type": "string",
  160. "name": "agent_type",
  161. "multiValueHandling": "SORTED_ARRAY",
  162. "createBitmapIndex": true
  163. }
  164. ],
  165. "dimensionExclusions": [
  166. "__time"
  167. ],
  168. "includeAllDimensions": false
  169. },
  170. "metricsSpec": [],
  171. "granularitySpec": {
  172. "type": "arbitrary",
  173. "queryGranularity": {
  174. "type": "none"
  175. },
  176. "rollup": false,
  177. "intervals": [
  178. "-146136543-09-08T08:23:32.096Z/146140482-04-24T15:36:27.903Z"
  179. ]
  180. },
  181. "transformSpec": {
  182. "filter": null,
  183. "transforms": []
  184. }
  185. },
  186. "columnMappings": [
  187. {
  188. "queryColumn": "timestamp",
  189. "outputColumn": "timestamp"
  190. },
  191. {
  192. "queryColumn": "agent_category",
  193. "outputColumn": "agent_category"
  194. },
  195. {
  196. "queryColumn": "agent_type",
  197. "outputColumn": "agent_type"
  198. }
  199. ],
  200. "tuningConfig": {
  201. "maxNumWorkers": 1,
  202. "maxRowsInMemory": 100000,
  203. "rowsPerSegment": 3000000
  204. }
  205. },
  206. "signature": [],
  207. "maxWorkerCount": 1
  208. },
  209. "phase": "FINISHED",
  210. "workerCount": 1,
  211. "partitionCount": 1,
  212. "startTime": "2022-09-14T22:12:31.602Z",
  213. "duration": 5891
  214. }
  215. ],
  216. "counters": {
  217. "0": {
  218. "0": {
  219. "input0": {
  220. "type": "channel",
  221. "rows": [
  222. 465346
  223. ],
  224. "files": [
  225. 1
  226. ],
  227. "totalFiles": [
  228. 1
  229. ]
  230. },
  231. "output": {
  232. "type": "channel",
  233. "rows": [
  234. 465346
  235. ],
  236. "bytes": [
  237. 43694447
  238. ],
  239. "frames": [
  240. 7
  241. ]
  242. },
  243. "shuffle": {
  244. "type": "channel",
  245. "rows": [
  246. 465346
  247. ],
  248. "bytes": [
  249. 41835307
  250. ],
  251. "frames": [
  252. 73
  253. ]
  254. },
  255. "sortProgress": {
  256. "type": "sortProgress",
  257. "totalMergingLevels": 3,
  258. "levelToTotalBatches": {
  259. "0": 1,
  260. "1": 1,
  261. "2": 1
  262. },
  263. "levelToMergedBatches": {
  264. "0": 1,
  265. "1": 1,
  266. "2": 1
  267. },
  268. "totalMergersForUltimateLevel": 1,
  269. "progressDigest": 1
  270. }
  271. }
  272. },
  273. "1": {
  274. "0": {
  275. "input0": {
  276. "type": "channel",
  277. "rows": [
  278. 465346
  279. ],
  280. "bytes": [
  281. 41835307
  282. ],
  283. "frames": [
  284. 73
  285. ]
  286. },
  287. "segmentGenerationProgress": {
  288. "type": "segmentGenerationProgress",
  289. "rowsProcessed": 465346,
  290. "rowsPersisted": 465346,
  291. "rowsMerged": 465346
  292. }
  293. }
  294. }
  295. }
  296. }
  297. }
  298. }

The following table describes the response fields when you retrieve a report for a MSQ task engine using the /druid/indexer/v1/task/<taskId>/reports endpoint:

FieldDescription
multiStageQuery.taskIdController task ID.
multiStageQuery.payload.statusQuery status container.
multiStageQuery.payload.status.statusRUNNING, SUCCESS, or FAILED.
multiStageQuery.payload.status.startTimeStart time of the query in ISO format. Only present if the query has started running.
multiStageQuery.payload.status.durationMsMilliseconds elapsed after the query has started running. -1 denotes that the query hasn’t started running yet.
multiStageQuery.payload.status.pendingTasksNumber of tasks that are not fully started. -1 denotes that the number is currently unknown.
multiStageQuery.payload.status.runningTasksNumber of currently running tasks. Should be at least 1 since the controller is included.
multiStageQuery.payload.status.errorReportError object. Only present if there was an error.
multiStageQuery.payload.status.errorReport.taskIdThe task that reported the error, if known. May be a controller task or a worker task.
multiStageQuery.payload.status.errorReport.hostThe hostname and port of the task that reported the error, if known.
multiStageQuery.payload.status.errorReport.stageNumberThe stage number that reported the error, if it happened during execution of a specific stage.
multiStageQuery.payload.status.errorReport.errorError object. Contains errorCode at a minimum, and may contain other fields as described in the error code table. Always present if there is an error.
multiStageQuery.payload.status.errorReport.error.errorCodeOne of the error codes from the error code table. Always present if there is an error.
multiStageQuery.payload.status.errorReport.error.errorMessageUser-friendly error message. Not always present, even if there is an error.
multiStageQuery.payload.status.errorReport.exceptionStackTraceJava stack trace in string form, if the error was due to a server-side exception.
multiStageQuery.payload.stagesArray of query stages.
multiStageQuery.payload.stages[].stageNumberEach stage has a number that differentiates it from other stages.
multiStageQuery.payload.stages[].phaseEither NEW, READING_INPUT, POST_READING, RESULTS_COMPLETE, or FAILED. Only present if the stage has started.
multiStageQuery.payload.stages[].workerCountNumber of parallel tasks that this stage is running on. Only present if the stage has started.
multiStageQuery.payload.stages[].partitionCountNumber of output partitions generated by this stage. Only present if the stage has started and has computed its number of output partitions.
multiStageQuery.payload.stages[].startTimeStart time of this stage. Only present if the stage has started.
multiStageQuery.payload.stages[].durationThe number of milliseconds that the stage has been running. Only present if the stage has started.
multiStageQuery.payload.stages[].sortA boolean that is set to true if the stage does a sort as part of its execution.
multiStageQuery.payload.stages[].definitionThe object defining what the stage does.
multiStageQuery.payload.stages[].definition.idThe unique identifier of the stage.
multiStageQuery.payload.stages[].definition.inputArray of inputs that the stage has.
multiStageQuery.payload.stages[].definition.broadcastArray of input indexes that get broadcasted. Only present if there are inputs that get broadcasted.
multiStageQuery.payload.stages[].definition.processorAn object defining the processor logic.
multiStageQuery.payload.stages[].definition.signatureThe output signature of the stage.

Cancel a query task

Request

  • HTTP
  • curl
  • Python
  1. POST /druid/indexer/v1/task/<taskId>/shutdown
  1. # Make sure you replace `username`, `password`, `your-instance`, `port`, and `taskId` with the values for your deployment.
  2. curl --location --request POST 'https://<username>:<password>@<your-instance>:<port>/druid/indexer/v1/task/<taskId>/shutdown'
  1. import requests
  2. # Make sure you replace `your-instance`, `port`, and `taskId` with the values for your deployment.
  3. url = "https://<your-instance>:<port>/druid/indexer/v1/task/<taskId>/shutdown"
  4. payload={}
  5. headers = {}
  6. response = requests.post(url, headers=headers, data=payload, auth=('USER', 'PASSWORD'))
  7. print(response.text)

Response

  1. {
  2. "task": "query-655efe33-781a-4c50-ae84-c2911b42d63c"
  3. }