Bu makalede, depolama hesabınızdan bir veri alt kümesini almak için sorgu hızlandırmanın nasıl kullanılacağı gösterilmektedir.
Sorgu hızlandırma, uygulamaların ve analiz çerçevelerinin yalnızca belirli bir işlemi gerçekleştirmek için ihtiyaç duydukları verileri alarak veri işlemeyi önemli ölçüde iyileştirmesini sağlar. Daha fazla bilgi edinmek için bkz. Azure Data Lake Storage Sorgu Hızlandırma.
Az modülünün 4.6.0 veya sonraki bir sürümünü yükleyin.
Install-Module -Name Az -Repository PSGallery -Force
Az'nin eski bir sürümünden güncelleştirmek için aşağıdaki komutu çalıştırın:
Update-Module -Name Az
Bir komut istemi açın ve dizini (cd) proje klasörünüzde değiştirin Örneğin:
cd myProject
12.5.0-preview.6 komutunu kullanarak Azure Blob depolama istemci kitaplığının .NET paketi için dotnet add package sürümünü veya daha sonrasını yükleyin.
dotnet add package Azure.Storage.Blobs -v 12.8.0
Bu makalede görüntülenen örnekler, CsvHelper kitaplığını kullanarak bir CSV dosyasını ayrıştırıyor. Bu kitaplığı kullanmak için aşağıdaki komutu kullanın.
dotnet add package CsvHelper
Projenizin pom.xml dosyasını bir metin düzenleyicisinde açın. Bağımlılık grubuna aşağıdaki bağımlılık öğelerini ekleyin.
<!-- Request static dependencies from Maven -->
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-blob</artifactId>
<version>12.8.0-beta.1</version>
</dependency>
Pip kullanarak Python için Azure Data Lake Storage istemci kitaplığını yükleyin.
pip install azure-storage-blob==12.4.0
Bir terminal penceresi açıp aşağıdaki komutu yazarak JavaScript için Data Lake istemci kitaplığını yükleyin.
npm install @azure/storage-blob
npm install @fast-csv/parse
Bu using deyimleri kod dosyanızın en üstüne ekleyin.
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
Sorgu hızlandırma, CSV ve JSON biçimli verileri elde eder. Bu nedenle, kullandığınız CSV veya JSON ayrıştırma kütüphaneleri için using ifadeleri eklediğinizden emin olun. Bu makalede görüntülenen örnekler, NuGet'te bulunan CsvHelper kitaplığını kullanarak bir CSV dosyasını ayrıştırır. Bu nedenle, bu using deyimleri kod dosyasının en üstüne ekleriz.
using CsvHelper;
using CsvHelper.Configuration;
Bu makalede sunulan örnekleri derlemek için bu using deyimleri de eklemeniz gerekir.
using System.Threading.Tasks;
using System.IO;
using System.Globalization;
Bu import deyimleri kod dosyanızın en üstüne ekleyin.
import com.azure.storage.blob.*;
import com.azure.storage.blob.options.*;
import com.azure.storage.blob.models.*;
import com.azure.storage.common.*;
import java.io.*;
import java.util.function.Consumer;
import org.apache.commons.csv.*;
Bu içeri aktarma deyimlerini kod dosyanızın en üstüne ekleyin.
import sys, csv
from azure.storage.blob import BlobServiceClient, ContainerClient, BlobClient, DelimitedTextDialect, BlobQueryError
storage-blob Bu deyimi kod dosyanızın en üstüne yerleştirerek modülü ekleyin.
const { BlobServiceClient } = require("@azure/storage-blob");
Sorgu hızlandırma, CSV ve JSON biçimli verileri elde eder. Bu nedenle, kullanmayı seçtiğiniz csv veya JSON ayrıştırma modülleri için deyimler eklediğinizden emin olun. Bu makalede görüntülenen örnekler , fast-csv modülünü kullanarak bir CSV dosyasını ayrıştıracaktır. Bu nedenle, bu deyimi kod dosyasının en üstüne ekleriz.
const csv = require('@fast-csv/parse');
Sorgu hızlandırma isteğinde satır filtresi koşullarını ve sütun projeksiyonlarını belirtmek için SQL kullanabilirsiniz. Aşağıdaki kod, depolamadaki bir CSV dosyasını sorgular ve üçüncü sütunun değeriyle Hemingway, Ernesteşleştiği tüm veri satırlarını döndürür.
Function Get-QueryCsv($ctx, $container, $blob, $query, $hasheaders) {
$tempfile = New-TemporaryFile
$informat = New-AzStorageBlobQueryConfig -AsCsv -HasHeader:$hasheaders -RecordSeparator "`n" -ColumnSeparator "," -QuotationCharacter """" -EscapeCharacter "\"
Get-AzStorageBlobQueryResult -Context $ctx -Container $container -Blob $blob -InputTextConfiguration $informat -OutputTextConfiguration (New-AzStorageBlobQueryConfig -AsCsv -HasHeader -RecordSeparator "`n" -ColumnSeparator "," -QuotationCharacter """" -EscapeCharacter "\") -ResultFile $tempfile.FullName -QueryString $query -Force
Get-Content $tempfile.FullName
}
$container = "data"
$blob = "csv/csv-general/seattle-library.csv"
Get-QueryCsv $ctx $container $blob "SELECT * FROM BlobStorage WHERE _3 = 'Hemingway, Ernest, 1899-1961'" $false
Zaman uyumsuz yöntem BlockBlobClient.QueryAsync sorguyu sorgu hızlandırma API'sine gönderir ve ardından sonuçları bir Akış nesnesi olarak uygulamaya geri gönderir.
static async Task QueryHemingway(BlockBlobClient blob)
{
string query = @"SELECT * FROM BlobStorage WHERE _3 = 'Hemingway, Ernest, 1899-1961'";
await DumpQueryCsv(blob, query, false);
}
private static async Task DumpQueryCsv(BlockBlobClient blob, string query, bool headers)
{
try
{
var options = new BlobQueryOptions()
{
InputTextConfiguration = new BlobQueryCsvTextOptions()
{
HasHeaders = true,
RecordSeparator = "\n",
ColumnSeparator = ",",
EscapeCharacter = '\\',
QuotationCharacter = '"'
},
OutputTextConfiguration = new BlobQueryCsvTextOptions()
{
HasHeaders = true,
RecordSeparator = "\n",
ColumnSeparator = ",",
EscapeCharacter = '\\',
QuotationCharacter = '"' },
ProgressHandler = new Progress<long>((finishedBytes) =>
Console.Error.WriteLine($"Data read: {finishedBytes}"))
};
options.ErrorHandler += (BlobQueryError err) => {
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine($"Error: {err.Position}:{err.Name}:{err.Description}");
Console.ResetColor();
};
// BlobDownloadInfo exposes a Stream that will make results available when received rather than blocking for the entire response.
using (var reader = new StreamReader((await blob.QueryAsync(
query,
options)).Value.Content))
{
using (var parser = new CsvReader
(reader, new CsvConfiguration(CultureInfo.CurrentCulture) { HasHeaderRecord = true }))
{
while (await parser.ReadAsync())
{
Console.Out.WriteLine(String.Join(" ", parser.Parser.Record));
}
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Exception: " + ex.ToString());
}
}
yöntemi BlockBlobClient.openInputStream() sorguyu sorgu hızlandırma API'sine gönderir ve ardından sonuçları, diğer InputStream nesneleri gibi okunabilen bir InputStream nesne olarak uygulamaya geri akışla gönderir.
static void QueryHemingway(BlobClient blobClient) {
String expression = "SELECT * FROM BlobStorage WHERE _3 = 'Hemingway, Ernest, 1899-1961'";
DumpQueryCsv(blobClient, expression, true);
}
static void DumpQueryCsv(BlobClient blobClient, String query, Boolean headers) {
try {
BlobQuerySerialization input = new BlobQueryDelimitedSerialization()
.setRecordSeparator('\n')
.setColumnSeparator(',')
.setHeadersPresent(headers)
.setFieldQuote('\0')
.setEscapeChar('\\');
BlobQuerySerialization output = new BlobQueryDelimitedSerialization()
.setRecordSeparator('\n')
.setColumnSeparator(',')
.setHeadersPresent(true)
.setFieldQuote('\0')
.setEscapeChar('\n');
Consumer<BlobQueryError> errorConsumer = System.out::println;
Consumer<BlobQueryProgress> progressConsumer = progress -> System.out.println("total bytes read: " + progress.getBytesScanned());
BlobQueryOptions queryOptions = new BlobQueryOptions(query)
.setInputSerialization(input)
.setOutputSerialization(output)
.setErrorConsumer(errorConsumer)
.setProgressConsumer(progressConsumer);
/* Open the query input stream. */
InputStream stream = blobClient.openQueryInputStream(queryOptions).getValue();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
/* Read from stream like you normally would. */
for (CSVRecord record : CSVParser.parse(reader, CSVFormat.EXCEL.withHeader())) {
System.out.println(record.toString());
}
}
} catch (Exception e) {
System.err.println("Exception: " + e.toString());
e.printStackTrace(System.err);
}
}
def query_hemingway(blob: BlobClient):
query = "SELECT * FROM BlobStorage WHERE _3 = 'Hemingway, Ernest, 1899-1961'"
dump_query_csv(blob, query, False)
def dump_query_csv(blob: BlobClient, query: str, headers: bool):
qa_reader = blob.query_blob(query, blob_format=DelimitedTextDialect(has_header=headers), on_error=report_error, encoding='utf-8')
# records() returns a generator that will stream results as received. It will not block pending all results.
csv_reader = csv.reader(qa_reader.records())
for row in csv_reader:
print("*".join(row))
Bu örnek sorguyu sorgu hızlandırma API'sine gönderir ve ardından sonuçların akışını geri alır.
blob Yardımcı işlevine queryHemingway geçirilen nesne BlockBlobClient türündedir.
BlockBlobClient nesnesi alma hakkında daha fazla bilgi edinmek için bkz. Hızlı Başlangıç: Node.js'de JavaScript v12 SDK ile blobları yönetme.
async function queryHemingway(blob)
{
const query = "SELECT * FROM BlobStorage WHERE _3 = 'Hemingway, Ernest, 1899-1961'";
await dumpQueryCsv(blob, query, false);
}
async function dumpQueryCsv(blob, query, headers)
{
var response = await blob.query(query, {
inputTextConfiguration: {
kind: "csv",
recordSeparator: '\n',
hasHeaders: headers
},
outputTextConfiguration: {
kind: "csv",
recordSeparator: '\n',
hasHeaders: true
},
onProgress: (progress) => console.log(`Data read: ${progress.loadedBytes}`),
onError: (err) => console.error(`Error: ${err.position}:${err.name}:${err.description}`)});
return new Promise(
function (resolve, reject) {
csv.parseStream(response.readableStreamBody)
.on('data', row => console.log(row))
.on('error', error => {
console.error(error);
reject(error);
})
.on('end', rowCount => resolve());
});
}
Sonuçlarınızın kapsamını bir sütun alt kümesi olarak belirleyebilirsiniz. Bu şekilde yalnızca belirli bir hesaplamayı gerçekleştirmek için gereken sütunları alırsınız. Bu, ağ üzerinden daha az veri aktarıldığı için uygulama performansını artırır ve maliyeti azaltır.
Function Get-QueryCsv($ctx, $container, $blob, $query, $hasheaders) {
$tempfile = New-TemporaryFile
$informat = New-AzStorageBlobQueryConfig -AsCsv -HasHeader:$hasheaders
Get-AzStorageBlobQueryResult -Context $ctx -Container $container -Blob $blob -InputTextConfiguration $informat -OutputTextConfiguration (New-AzStorageBlobQueryConfig -AsCsv -HasHeader) -ResultFile $tempfile.FullName -QueryString $query -Force
Get-Content $tempfile.FullName
}
$container = "data"
$blob = "csv/csv-general/seattle-library-with-headers.csv"
Get-QueryCsv $ctx $container $blob "SELECT BibNum FROM BlobStorage" $true
static async Task QueryBibNum(BlockBlobClient blob)
{
string query = @"SELECT BibNum FROM BlobStorage";
await DumpQueryCsv(blob, query, true);
}
static void QueryBibNum(BlobClient blobClient)
{
String expression = "SELECT BibNum FROM BlobStorage";
DumpQueryCsv(blobClient, expression, true);
}
def query_bibnum(blob: BlobClient):
query = "SELECT BibNum FROM BlobStorage"
dump_query_csv(blob, query, True)
async function queryBibNum(blob)
{
const query = "SELECT BibNum FROM BlobStorage";
await dumpQueryCsv(blob, query, true);
}
Aşağıdaki kod, satır filtreleme ve sütun projeksiyonlarını aynı sorguda birleştirir.
Get-QueryCsv $ctx $container $blob $query $true
Function Get-QueryCsv($ctx, $container, $blob, $query, $hasheaders) {
$tempfile = New-TemporaryFile
$informat = New-AzStorageBlobQueryConfig -AsCsv -HasHeader:$hasheaders
Get-AzStorageBlobQueryResult -Context $ctx -Container $container -Blob $blob -InputTextConfiguration $informat -OutputTextConfiguration (New-AzStorageBlobQueryConfig -AsCsv -HasHeader) -ResultFile $tempfile.FullName -QueryString $query -Force
Get-Content $tempfile.FullName
}
$container = "data"
$query = "SELECT BibNum, Title, Author, ISBN, Publisher, ItemType
FROM BlobStorage
WHERE ItemType IN
('acdvd', 'cadvd', 'cadvdnf', 'calndvd', 'ccdvd', 'ccdvdnf', 'jcdvd', 'nadvd', 'nadvdnf', 'nalndvd', 'ncdvd', 'ncdvdnf')"
static async Task QueryDvds(BlockBlobClient blob)
{
string query = @"SELECT BibNum, Title, Author, ISBN, Publisher, ItemType
FROM BlobStorage
WHERE ItemType IN
('acdvd', 'cadvd', 'cadvdnf', 'calndvd', 'ccdvd', 'ccdvdnf', 'jcdvd', 'nadvd', 'nadvdnf', 'nalndvd', 'ncdvd', 'ncdvdnf')";
await DumpQueryCsv(blob, query, true);
}
static void QueryDvds(BlobClient blobClient)
{
String expression = "SELECT BibNum, Title, Author, ISBN, Publisher, ItemType " +
"FROM BlobStorage " +
"WHERE ItemType IN " +
" ('acdvd', 'cadvd', 'cadvdnf', 'calndvd', 'ccdvd', 'ccdvdnf', 'jcdvd', 'nadvd', 'nadvdnf', 'nalndvd', 'ncdvd', 'ncdvdnf')";
DumpQueryCsv(blobClient, expression, true);
}
def query_dvds(blob: BlobClient):
query = "SELECT BibNum, Title, Author, ISBN, Publisher, ItemType "\
"FROM BlobStorage "\
"WHERE ItemType IN "\
" ('acdvd', 'cadvd', 'cadvdnf', 'calndvd', 'ccdvd', 'ccdvdnf', 'jcdvd', 'nadvd', 'nadvdnf', 'nalndvd', 'ncdvd', 'ncdvdnf')"
dump_query_csv(blob, query, True)
async function queryDvds(blob)
{
const query = "SELECT BibNum, Title, Author, ISBN, Publisher, ItemType " +
"FROM BlobStorage " +
"WHERE ItemType IN " +
" ('acdvd', 'cadvd', 'cadvdnf', 'calndvd', 'ccdvd', 'ccdvdnf', 'jcdvd', 'nadvd', 'nadvdnf', 'nalndvd', 'ncdvd', 'ncdvdnf')";
await dumpQueryCsv(blob, query, true);
}