데이터 쿼리
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
이 페이지에서는 차트 도구 데이터 소스 프로토콜을 지원하는 데이터 소스에 쿼리를 보내는 방법을 설명합니다.
목차
개요
데이터 소스는 차트 도구의 데이터 소스 프로토콜을 지원하는 웹 서비스입니다. 데이터 소스에 SQL 쿼리를 전송할 수 있으며, 이에 대한 응답으로 적절한 정보가 채워진 DataTable이 수신됩니다. 데이터 소스의 예로는 Google 스프레드시트와 SalesForce가 있습니다.
요청 보내기
요청을 보내려면 다음 안내를 따르세요.
-
데이터 소스의 URL을 사용하여 Query 객체를 인스턴스화합니다. URL은 해당 데이터 소스에서 이해할 수 있는 구문으로 요청되는 데이터를 나타내야 합니다.
-
원하는 경우
Query
객체 생성자에서 메서드를 두 번째 매개변수로 보내는 등의 요청 옵션을 지정합니다 (자세한 내용은 쿼리 생성자의 opt_options
매개변수 참조).
-
필요한 경우 쿼리 언어 문자열을 추가하여 결과를 정렬하거나 필터링한 후 요청을 보냅니다. 차트 도구의 데이터 소스 쿼리 언어를 지원하는 데 데이터 소스가 필요하지는 않습니다. 데이터 소스가 쿼리 언어를 지원하지 않으면 SQL 쿼리 문자열을 무시하지만 여전히
DataTable
을 반환합니다. 쿼리 언어는 SQL 언어 변형입니다. 여기에서 전체 쿼리 언어 구문을 확인하세요.
-
응답을 수신하면 호출될 콜백 핸들러를 지정하여 쿼리를 전송합니다. 자세한 내용은 다음 섹션을 참고하세요.
다음은 Google 스프레드시트 셀 범위의 데이터 요청을 보내는 예입니다. Google 스프레드시트의 URL을 가져오는 방법은 여기를 참고하세요.
function initialize() {
var opts = {sendMethod: 'auto'};
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('http://spreadsheets.google.com?key=123AB&...', opts);
// Optional request to return only column C and the sum of column B, grouped by C members.
query.setQuery('select C, sum(B) group by C');
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Called when the query response is returned.
...
}
Apps Script 내에서 쿼리를 전송하는 경우 IFRAME
모드를 사용해야 합니다.
응답 처리
요청이 반환되면 응답 핸들러 함수가 호출됩니다. 응답 핸들러 함수에 전달되는 매개변수는 google.visualization.QueryResponse 유형입니다.
요청이 성공하면 응답에 데이터 테이블(google.visualization.DataTable
클래스)이 포함됩니다. 요청이 실패하면 응답에 오류 관련 정보가 포함되고 DataTable
는 포함되지 않습니다.
응답 핸들러는 다음을 실행해야 합니다.
-
response.isError()
를 호출하여 요청의 성공 또는 실패 여부를 확인합니다.
사용자에게는 오류 메시지를 표시할 필요가 없습니다. 시각화 라이브러리는 컨테이너 <div>
에 오류 메시지를 표시합니다. 그러나 오류를 수동으로 처리하려는 경우
goog.visualization.errors
클래스를 사용하여 커스텀 메시지를 표시할 수 있습니다 (커스텀 오류 처리의 예시는 쿼리 래퍼 예 참조).
-
요청이 성공하면
getDataTable()
를 호출하여 검색할 수 있는 DataTable
가 응답에 포함됩니다. 차트에 전달합니다.
다음 코드는 원형 차트를 그리는 이전 요청을 처리하는 방법을 보여줍니다.
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true});
}
CSV 파일 읽기
CSV (쉼표로 구분된 값) 데이터로 차트를 만들려는 경우 두 가지 방법이 있습니다. CSV 데이터를 수동으로 Google 차트 데이터 테이블 형식으로 변환하거나, 차트를 제공하는 웹 서버에 CSV 파일을 배치하고 이 페이지의 기법을 사용하여 쿼리합니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2024-07-10(UTC)
[null,null,["최종 업데이트: 2024-07-10(UTC)"],[[["\u003cp\u003eThis page explains how to send a SQL query to a Datasource, a web service supporting the Chart Tools Datasource protocol, to receive a DataTable with the requested data.\u003c/p\u003e\n"],["\u003cp\u003eYou can use a Query object to send a request with optional parameters for sending method and a query language string for filtering data, receiving a response handled by a callback function.\u003c/p\u003e\n"],["\u003cp\u003eThe response handler checks for errors and, if successful, retrieves the DataTable from the QueryResponse for use in visualizations like charts.\u003c/p\u003e\n"],["\u003cp\u003eCSV data can be either manually converted to Google Charts datatable format or placed on a web server and queried using the techniques described on the page.\u003c/p\u003e\n"],["\u003cp\u003eMore detailed information on query language syntax, the Query class, and the QueryResponse class can be found via provided links.\u003c/p\u003e\n"]]],[],null,["# Data Queries\n\nThis page describes how to send a query to a data source that supports the Chart Tools Datasource\nprotocol.\n\nContents\n--------\n\n1. [Overview](#overview)\n2. [Sending a request](#Sending_a_Query)\n3. [Processing the response](#Processing_the_Query_Response)\n4. [Reading CSV files](#csv)\n5. [More information](#moreinfo)\n\nOverview\n--------\n\n\nA Datasource is a web service that supports the Chart Tools Datasource protocol. You can send a\nSQL query to a Datasource, and in response you will receive a DataTable populated with the\nappropriate information. Some examples of Datasources include\n[Google Spreadsheets](/chart/interactive/docs/spreadsheets) and SalesForce.\n\nSending a request\n-----------------\n\n**To send a request:**\n\n1. Instantiate a [Query](/chart/interactive/docs/reference#Query) object with the URL of your Datasource. The URL should indicate what data is being requested, in a syntax understood by that data source.\n2. Optionally specify request options such as sending method as an optional second parameter in the `Query` object constructor (see the Query constructor's [`opt_options`](/chart/interactive/docs/reference#Query) parameter for details):\n3. Optionally add a [query language string](/chart/interactive/docs/querylanguage) to sort or filter the results, and then send the request. Datasources are not required to support the Chart Tools Datasource query language. If the Datasource does not support the query language, it will ignore the SQL query string, but still return a `DataTable`. The query language is a SQL language variant; read the full [query language syntax here](/chart/interactive/docs/querylanguage).\n4. Send the query, specifying a callback handler that will be called when the response is received: see next section for details.\n\n\nHere's an example of sending a request for data in a Google Spreadsheet cell range; to learn how\nto get the URL for a Google Spreadsheet, see\n[here](/chart/interactive/docs/spreadsheets#Google_Spreadsheets_as_a_Data_Source): \n\n```gdscript\nfunction initialize() {\n var opts = {sendMethod: 'auto'};\n // Replace the data source URL on next line with your data source URL.\n var query = new google.visualization.Query('http://spreadsheets.google.com?key=123AB&...', opts);\n\n // Optional request to return only column C and the sum of column B, grouped by C members.\n query.setQuery('select C, sum(B) group by C');\n\n // Send the query with a callback function.\n query.send(handleQueryResponse);\n}\n\nfunction handleQueryResponse(response) {\n // Called when the query response is returned.\n ...\n}\n```\n\nIf you are sending your query from within Apps Script, be sure to use [`IFRAME` mode](/apps-script/reference/html/sandbox-mode).\n\nProcessing the response\n-----------------------\n\n\nYour response handler function will be called when the request returns. The parameter passed in\nto your response handler function is of type\n[google.visualization.QueryResponse](/chart/interactive/docs/reference#QueryResponse).\nIf the request was successful, the response contains a data table\n(class `google.visualization.DataTable`). If the request failed, the response contains\ninformation about the error, and no `DataTable`.\n\n**Your response handler should do the following:**\n\n1. Check whether the request succeeded or failed by calling `response.isError()`. You shouldn't need to display any error messages to the user; the Visualization library will display an error message for you in your container `\u003cdiv\u003e`. However, if you do want to handle errors manually, you can use the [`goog.visualization.errors`](/chart/interactive/docs/reference#errordisplay) class to display custom messages (see the [Query Wrapper Example](/chart/interactive/docs/examples#querywrapper) for an example of custom error handling).\n2. If the request succeeded, the response will include a `DataTable` that you can retrieve by calling `getDataTable()`. Pass it to your chart.\n\nThe following code demonstrates handling the previous request to draw a pie chart: \n\n```gdscript\nfunction handleQueryResponse(response) {\n\n if (response.isError()) {\n alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());\n return;\n }\n\n var data = response.getDataTable();\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, {width: 400, height: 240, is3D: true});\n}\n```\n\nReading CSV files\n-----------------\n\nIf you want to build a chart out of CSV (comma-separated values)\ndata, you have two choices. Either manually convert the CSV data into\nthe [Google\nCharts datatable format](/chart/interactive/docs/datatables_dataviews#creatingpopulating), or place the CSV file on the web server\nserving the chart, and query it using the technique on this page.\n\nMore information\n----------------\n\n- [Query Language Syntax](/chart/interactive/docs/querylanguage) - Describes the syntax of the language used to make data queries.\n- [Query Class](/chart/interactive/docs/reference#Query) - Reference page for the class that wraps a query.\n- [QueryResponse Class](/chart/interactive/docs/reference#QueryResponse) - Reference page for the class that wraps the response to a query."]]