#integertype
Explore tagged Tumblr posts
arshikasingh · 11 months ago
Text
Example of Returning an Array of Integer Type in Java
Let us see an example on how to return an array of integer type in Java:
Tumblr media
1 note · View note
nitorinfotech-blog · 4 years ago
Text
Data Processing with Apache Spark
Spark has emerged as a favorite for analytics, especially those that can handle massive volumes of data as well as provide high performance compared to any other conventional database engines. Spark SQL allows users to formulate their complex business requirements to Spark by using the familiar language of SQL.
Tumblr media
So, in this blog, we will see how you can process data with Apache Spark and what better way to establish the capabilities of Spark than to put it through its paces and use the Hadoop-DS benchmark to compare performance, throughput, and SQL compatibility against SQL Server.
Before we begin, ensure that the following test environment is available:
SQL Server: 32 GB RAM with Windows server 2012 R2
Hadoop Cluster: 2 machines with 8GB RAM Ubuntu flavor
Sample Data:
For the purpose of this demo, we will use AdventureWorks2016DW data.
Following table is used in query with no of records:
Tumblr media
We will compare performance of three data processing engines, which are SQL Server, Spark with CSV files as datafiles and Spark with Parquet files as datafiles.
Query:
We will use the following query to process data:
select pc.EnglishProductCategoryName, ps.EnglishProductSubcategoryName, sum(SalesAmount)
from FactInternetSales f
inner join dimProduct p on f.productkey = p.productkey
inner join DimProductSubcategory ps on p.ProductSubcategoryKey = ps.ProductSubcategoryKey
inner join DimProductCategory pc on pc.ProductCategoryKey = ps.ProductCategoryKey
inner join dimcustomer c on c.customerkey = f.customerkey
group by pc.EnglishProductCategoryName, ps.EnglishProductSubcategoryName  
 Let’s measure the performance of each processing engine:
1) SQL Server:
While running query in SQL Server with the 32GB RAM Microsoft 2012 Server, it takes around 2.33 mins to execute and return the data.
Following is the screenshot for the same:
2) Spark with CSV data files:
Now let’s export the same dataset to CSV and move it to HDFS.
Following is the screenshot of HDFS with the CSV file as an input source.
Now that we have the files for the specific input tables moved to HDFS as CSV files, we can start with Spark Shell and create DataFrames for each source file.
Run Following commands for creating SQL Context:
import org.apache.spark.sql.types._
import org.apache.spark.sql.{Row, SQLContext}
val sqlContext = new SQLContext(sc)
Run following command to create Fact Schema :
val factSchema = StructType(Array(
StructField("ProductKey", IntegerType, true),
StructField("OrderDateKey", IntegerType, true),
StructField("DueDateKey", IntegerType, true),
StructField("ShipDateKey", IntegerType, true),
StructField("CustomerKey", IntegerType, true),
StructField("PromotionKey", IntegerType, true),
StructField("CurrencyKey", IntegerType, true),
StructField("SalesTerritoryKey", IntegerType, true),
StructField("SalesOrderNumber", StringType, true),
StructField("SalesOrderLineNumber", IntegerType, true),
StructField("RevisionNumber", IntegerType, true),
StructField("OrderQuantity", IntegerType, true),
StructField("UnitPrice", DoubleType, true),
StructField("ExtendedAmount", DoubleType, true),
StructField("UnitPriceDiscountPct", DoubleType, true),
StructField("DiscountAmount", DoubleType, true),
StructField("ProductStandardCost", DoubleType, true),
StructField("TotalProductCost", DoubleType, true),
StructField("SalesAmount", DoubleType, true),
StructField("TaxAmt", DoubleType, true),
StructField("Freight", DoubleType, true),
StructField("CarrierTrackingNumber", StringType, true),
StructField("CustomerPONumber", StringType, true),
StructField("OrderDate", TimestampType, true),
StructField("DueDate", TimestampType, true),
StructField("ShipDate", TimestampType, true)
));
Run following command to create a DataFrame for Sales with Fact Schema:
val salesCSV = sqlContext.read.format("csv")
.option("header", "false")
.schema(factSchema)
.load("/data/FactSalesNew/part-m-00000")
Run following command to create Customer schema:
val customerSchema = StructType(Array(
StructField("CustomerKey", IntegerType, true),
StructField("GeographyKey", IntegerType, true),
StructField("CustomerAlternateKey", StringType, true),
StructField("Title", StringType, true),
StructField("FirstName", StringType, true),
StructField("MiddleName", StringType, true),
StructField("LastName", StringType, true),
StructField("NameStyle", BooleanType, true),
StructField("BirthDate", TimestampType, true),
StructField("MaritalStatus", StringType, true),
StructField("Suffix", StringType, true),
StructField("Gender", StringType, true),
StructField("EmailAddress", StringType, true),
StructField("YearlyIncome", DoubleType, true),
StructField("TotalChildren", IntegerType, true),
StructField("NumberChildrenAtHome", IntegerType, true),
StructField("EnglishEducation", StringType, true),
StructField("SpanishEducation", StringType, true),
StructField("FrenchEducation", StringType, true),
StructField("EnglishOccupation", StringType, true),
StructField("SpanishOccupation", StringType, true),
StructField("FrenchOccupation", StringType, true),
StructField("HouseOwnerFlag", StringType, true),
StructField("NumberCarsOwned", IntegerType, true),
StructField("AddressLine1", StringType, true),
StructField("AddressLine2", StringType, true),
StructField("Phone", StringType, true),
StructField("DateFirstPurchase", TimestampType, true),
StructField("CommuteDistance", StringType, true)
));
Run following command to create Customer a dataframe with Customer Schema.
 val customer = sqlContext.read.format("csv")
.option("header", "false")
.schema(customerSchema)
.load("/data/dimCustomer/part-m-00000")
 Now create product schema with the following command:
 val productSchema = StructType(Array(
StructField("ProductKey", IntegerType, true),
StructField("ProductAlternateKey", StringType, true),
StructField("ProductSubcategoryKey", IntegerType, true),
StructField("WeightUnitMeasureCode", StringType, true),
StructField("SizeUnitMeasureCode", StringType, true),
StructField("EnglishProductName", StringType, true),
StructField("SpanishProductName", StringType, true),
StructField("FrenchProductName", StringType, true),
StructField("StandardCost", DoubleType, true),
StructField("FinishedGoodsFlag", BooleanType, true),
StructField("Color", StringType, true),
StructField("SafetyStockLevel", IntegerType, true),
StructField("ReorderPoint", IntegerType, true),
StructField("ListPrice", DoubleType, true),
StructField("Size", StringType, true),
StructField("SizeRange", StringType, true),
StructField("Weight", DoubleType, true),
StructField("DaysToManufacture", IntegerType, true),
StructField("ProductLine", StringType, true),
StructField("DealerPrice", DoubleType, true),
StructField("Class", StringType, true),
StructField("Style", StringType, true),
StructField("ModelName", StringType, true),
StructField("LargePhoto", StringType, true),
StructField("EnglishDescription", StringType, true),
StructField("FrenchDescription", StringType, true),
StructField("ChineseDescription", StringType, true),
StructField("ArabicDescription", StringType, true),
StructField("HebrewDescription", StringType, true),
StructField("ThaiDescription", StringType, true),
StructField("GermanDescription", StringType, true),
StructField("JapaneseDescription", StringType, true),
StructField("TurkishDescription", StringType, true),
StructField("StartDate", TimestampType, true),
StructField("EndDate", TimestampType, true),
StructField("Status", StringType, true)
))
 Create product data frame with Product schema.
val product = sqlContext.read.format("csv")
.option("header", "false")
.schema(productSchema)
.load("/data/dimProduct/part-m-00000")
 Now create Product Category schema using following command:
val productCategotySchema = StructType(Array(
StructField("ProductCategoryKey", IntegerType, true),
StructField("ProductCategoryAlternateKey", IntegerType, true),
StructField("EnglishProductCategoryName", StringType, true),
StructField("SpanishProductCategoryName", StringType, true),
StructField("FrenchProductCategoryName", StringType, true)
))
Now create Product Category Data frame with ProductCategory Schema:
val productCategory = sqlContext.read.format("csv")
.option("header", "false")
.schema(productCategotySchema)
.load("/data/dimProductCategory/part-m-00000")
 Now create Product Sub Category schema using following command:
val productSubCategotySchema = StructType(Array(
StructField("ProductSubcategoryKey", IntegerType, true),
StructField("ProductSubcategoryAlternateKey", IntegerType, true),
StructField("EnglishProductSubcategoryName", StringType, true),
StructField("SpanishProductSubcategoryName", StringType, true),
StructField("FrenchProductSubcategoryName", StringType, true),
StructField("ProductCategoryKey", IntegerType, true)
))
And create productsubcategory data frame using below command:
val productSubCategory = sqlContext.read.format("csv")
.option("header", "false")
.schema(productSubCategotySchema)
.load("/data/dimProductSubCategory/part-m-00000")
 Now create temporary views of each data frame that we have created so far:
sales.createOrReplaceTempView("salesV")
customer.createOrReplaceTempView("customerV")
product.createOrReplaceTempView("productV")
productCategory.createOrReplaceTempView("productCategoryV")
productSubCategory.createOrReplaceTempView("productSubCategoryV")
And Run the same query which we ran in SQL Server:
Val df_1=spark.sql("""select pc.EnglishProductCategoryName, ps.EnglishProductSubcategoryName, sum(SalesAmount)
from salesV f
inner join productV p on f.productkey = p.productkey
inner join productSubCategoryV ps on p.ProductSubcategoryKey = ps.ProductSubcategoryKey
inner join productCategoryV pc on pc.ProductCategoryKey = ps.ProductCategoryKey
inner join customerV c on c.customerkey = f.customerkey
group by pc.EnglishProductCategoryName, ps.EnglishProductSubcategoryName """)
df_1.show()
It took around 3 mins to execute the result set.
3)Spark with Parquet file for Fact Table:
Now, let’s convert FactInternetSaleNew file to parquet file and save to hdfs using the following command:
salesCSV.write.format("parquet").save("sales_parquet")
Create dataframe on top of Parquet file using below command:
val sales = sqlContext.read.parquet("/user/nituser/sales.parquet")
And create temp view using sales data frame:
sales.createOrReplaceTempView("salesV")
Now, we will run the same query which we used in step 2:
val df_1=spark.sql("""select pc.EnglishProductCategoryName, ps.EnglishProductSubcategoryName, sum(SalesAmount)
from salesV f
inner join productV p on f.productkey = p.productkey
inner join productSubCategoryV ps on p.ProductSubcategoryKey = ps.ProductSubcategoryKey
inner join productCategoryV pc on pc.ProductCategoryKey = ps.ProductCategoryKey
inner join customerV c on c.customerkey = f.customerkey
group by pc.EnglishProductCategoryName, ps.EnglishProductSubcategoryName """)
 It will return the same result set in less than 20 secs.
We can conclude by stating that Spark with commodity hardware performs very similar to the high-end server of SQL Server. However, Spark outshines other engines when it deals with column-oriented efficient and compressed storage format.
So, we need to decide the specifications for the processing engine and storage based on business requirements, while also understanding how we can boost the power of such a highly efficient processing engine and get the required performance.
Reach out to us at Nitor Infotech know more about Apache Spark and how you can utilize it to accelerate your business and make advanced analytics more innovative.
0 notes
mjliu · 6 years ago
Text
maiden voyage with word2vec on spark
from pyspark.ml.feature import Tokenizer, RegexTokenizer from pyspark.ml.feature import StopWordsRemover from pyspark.sql.functions import col, udf from pyspark.sql.types import IntegerType from pyspark.ml.feature import Word2Vec from pyspark.sql import SparkSession import numpy as np import pandas as pd spark = SparkSession.builder.appName('abc').getOrCreate() sc = spark.sparkContext l = pd.DataFrame((['hello world', 1], ['alice wonderland', 2], ['simplicity is thy ultimate sophisitication', 3])) df = spark.createDataFrame(l) in_col = df.columns[0] regexTokenizer = RegexTokenizer(inputCol=in_col, outputCol='words', pattern='\\W') regexTokenized = regexTokenizer.transform(df) # remove stop words though not necessary remover = StopWordsRemover(inputCol='words', outputCol='filtered') filtered = remover.transform(regexTokenized) word2vec = Word2Vec(vectorSize = 20, minCount = 1, inputCol = 'filtered', outputCol = 'result') model = word2vec.fit(filtered) result = model.transform(filtered) V = model.getVectors() # find top 3 synonyms model.findSynonyms('simplicity', 3) # f.... sync as spark bug insync V.sql_ctx.sparkSession._jsparkSession = spark._jsparkSession V._sc = spark._sc # put results into local pandas V_pd = V.toPandas() spark.stop()
0 notes
jobssss · 8 years ago
Link
Question is somewhat unclear, but if you're looking for a way to "flatten" a DataFrame schema (i.e. get an array of all non-struct fields), here's one:
def flatten(schema: StructType): Array[StructField] = schema.fields.flatMap { f =>  f.dataType match {    case struct: StructType => flatten(struct)    case _ => Array(f)  } }
For example:
val schema = StructType(Seq(StructField("events",  StructType(Seq(    StructField("beaconVersion", IntegerType, true),    StructField("client", StringType, true),    StructField("data", StructType(Seq(      StructField("ad", StructType(Seq(        StructField("adId", StringType, true)      )))    )))  ))) )) println(flatten(schema).toList) // List(StructField(beaconVersion,IntegerType,true), StructField(client,StringType,true), StructField(adId,StringType,true))
0 notes
bigdataschool-moscow · 5 years ago
Text
Natural Language Processing (NLP) в PySpark: токенизация, стоп-слова, N-граммы
Tumblr media
Обработка естественного языка (Natural Language Processing, NLP) является перспективным направлением Data Science и Big Data. Сегодня мы расскажем вам о применении методов NLP в PySpark. В этой статье вы узнаете об обычной токенизации и на основе регуля��ных выражений, стоп-словах русского и английского языков, а также о N-граммах в PySpark.
Токенизация в PySpark
Токенизация — это процесс разбиения текста на текстовые единицы (чаще всего слова). В PySpark за это отвечают Tokenizer и RegexTokenizer. Создадим DataFrame, который состоит из простых предложений, а также определим функцию (udf), которая будет считать количество слов в списке. from pyspark.ml.feature import Tokenizer, RegexTokenizer  from pyspark.sql.functions import col, udf  from pyspark.sql.types import IntegerType  sentenceDataFrame = spark.createDataFrame([  (0, "Привет я слышал о NLP PySpark"),  (1, "Как же хочется попасть на Big Data курсы"),  (2, "Модели,линейной,регрессии,очень,хороши")  ], ["id", "sentence"])  countTokens = udf(lambda words: len(words), IntegerType()) Tokenizer разбивает текст на слова, разделённые пробелом. Ниже код на Python это демонстрирует. Как видим, последнюю строку он посчитал за один токен, потому что в этом тексте нет пробелов. tokenizer = Tokenizer(inputCol="sentence", outputCol="words")  tokenized = tokenizer.transform(sentenceDataFrame)  tokenized.select("sentence", "words")\  .withColumn("tokens", countTokens(col("words"))).show(truncate=False)  +-------------------------------------------------+------+ |words |tokens|  +-------------------------------------------------+------+ |[привет, я, слышал, о, nlp, pyspark] |6 | |[как, же, хочется, попасть, на, big, data, курсы]|8 |  |[модели,линейной,регрессии,очень,хороши] |1 |  +-------------------------------------------------+------+ На практике лучше применять RegexTokenizer, который позволяет проводить токенизацию на основе регулярных выражений. Параметр pattern используется в качестве разделителя. По умолчанию pattern имеет значение "\\s+" (пробел), т.е. ничем не отличается от обычного Tokenizer. Но мы можем разбить текст на слова с учётом запятых: regexTokenizer = RegexTokenizer(inputCol="sentence", outputCol="words", pattern=r"[,\s]")  regexTokenized = regexTokenizer.transform(sentenceDataFrame)  regexTokenized.select("sentence", "words") \  .withColumn("tokens", countTokens(col("words"))).show(truncate=False) +-------------------------------------------------+------+ |words |tokens| +-------------------------------------------------+------+  |[привет, я, слышал, о, nlp, pyspark] |6 |  |[как, же, хочется, попасть, на, big, data, курсы]|8 |  |[модели, линейной, регрессии, очень, хороши] |5 |  +-------------------------------------------------+------+ Следует, однако, быть острожным с регулярными выражениями, если работаете с кириллицей. Например, \W (не слово) найдёт не только знаки препинания и цифры, но и кириллические буквы.
Удаление стоп-слов
Многие алгоритмы Machine Learning очень чувствительны к шумам. В NLP к таким шумам относятся стоп-слова. Чаще всего это слова, которые не несут большой информативной нагрузки. В PySpark для удаления стоп-слов используется класс StopWordsRemover. StopWordsRemover принимает список слов, а не строку (str), поэтому предварительно следует токенизировать текст, как это было описано выше. Вот так в Python выглядит удаление стоп-слов для английского языка: from pyspark.ml.feature import StopWordsRemover  sentenceData = spark.createDataFrame([  (0, ["I", "saw", "the", "red", "balloon"]),  (1, ["Mary", "had", "a", "little", "lamb"])  ], ["id", "raw"]) remover = StopWordsRemover(inputCol="raw", outputCol="filtered")  remover.transform(sentenceData).show()  +---+----------------------------+--------------------+  |id |raw |filtered | +---+----------------------------+--------------------+ |0 |[I, saw, the, red, balloon] |[saw, red, balloon] | |1 |[Mary, had, a, little, lamb]|[Mary, little, lamb]|  +---+----------------------------+--------------------+ Для русского языка в PySpark есть специальный список стоп-слов, доступный через loadDefaultStopWords(language). Например, для токенизированного выше текста на русском (regexTokenized) удаление стоп-слов выглядит следующим образом: rus_stopwords = StopWordsRemover.loadDefaultStopWords("russian")  remover = StopWordsRemover( inputCol="words",  outputCol="filtered", stopWords=rus_stopwords)  remover.transform(regexTokenized).show()  +-------------------------------------------------+--------------------------------------------+  |words |filtered | +-------------------------------------------------+--------------------------------------------+ | [привет, я, слышал, о, nlp, pyspark] |[привет, слышал, nlp, pyspark] |  |[как, же, хочется, попасть, на, big, data, курсы]|[хочется, попасть, big, data, курсы] |  |[модели, линейной, регрессии, очень, хороши] |[модели, линейной, регрессии, очень, хороши]|  +-------------------------------------------------+--------------------------------------------+
Разбиение на N-граммы
Ещё один полезным инструментом NLP является разбиение слов на N-граммы — группы последовательных слов, которые можно извлечь из текстов. N-граммы позволяют сохранить контекст, поскольку становится известно, какое слово идёт следующим. Для этого в PySpark используется Ngram, который принимает список слов, поэтому текст следует также предварительно следует токенизировать. Ngram не зависит от языка. Вот так в Python выглядит извлечение биграмм (би = 2): from pyspark.ml.feature import NGram  wordDataFrame = spark.createDataFrame([  (0, ["Привет", "Я", "слышал", "о", "Spark"]),  (1, ["PySpark", "NLP", "это", "очень", "просто", "если", "подумать"]),  (2, ["Модели", "линейной", "регрессии", "просты"])  ], ["id", "words"])  ngram = NGram(n=2, inputCol="words", outputCol="ngrams")  ngramDataFrame = ngram.transform(wordDataFrame)  ngramDataFrame.select("ngrams").show()  +---------------------------------------------------------------------------+ |ngrams | +---------------------------------------------------------------------------+  |[Привет Я, Я слышал, слышал о, о Spark] |  |[PySpark NLP, NLP это, это очень, очень просто, просто если, если подумать]| |[Модели линейной, линейной регрессии, регрессии просты] | +---------------------------------------------------------------------------+ На этом примере видно, что «регрессия» теперь ассоциируется со словом «линейная». О предобработке текстов в рамках NLP с помощью PySpark вы узнаете на специализированном курсе «NLP – обработка естественного языка с Python» в нашем лицензированном учебном центре обучения и повышения квалификации разработчиков, менеджеров, архитекторов, инженеров, администраторов, Data Scientist’ов и аналитиков Big Data в Москве. Смотреть расписание Записаться на курс Источники https://spark.apache.org/docs/latest/ml-features.html Read the full article
0 notes
bigdataschool-moscow · 6 years ago
Text
Cassandra
Tumblr media
Apache Cassandra – это нереляционная отказоустойчивая распределенная СУБД, рассчитанная на создание высокомасштабируемых и надёжных хранилищ огромных массивов данных, представленных в виде хэша. Проект был разработан на языке Java в корпорации Facebook в 2008 году, и передан фонду Apache Software Foundation в 2009 . Эта СУБД относится к гибридным NoSQL-решениям, поскольку она сочетает модель хранения данных на базе семейства столбцов (ColumnFamily) с концепцией key-value (ключ-значение) .
Модель данных Apache Cassandra
Модель данных Cassandra состоит из следующих элементов [3]: ·       столбец или колонка (column) – ячейка с данными, включающая 3 части – имя (column name) в виде массива байтов, метку времени (timestamp) и само значение (value) также в виде байтового массива. С каждым значением связана метка времени — задаваемое пользователем 64-битное число, которое используется ��ля разрешения конфликтов во время записи: чем оно больше, тем новее считается столбец. Это учитывается при удалении старых колонок. ·       строка или запись (row) – именованная коллекция столбцов; ·       семейство столбцов (column family) – именованная коллекция строк; ·       пространство ключей (keyspace) – группа из нескольких семейств столбцов, собранных вместе. Оно логически группирует семейства столбцов и обеспечивает изолированные области имен.   Также стоит отметить понятия сравнителя (comparator), задаваемого для имени столбца и валидатора (validator) для значений и ключей. Comparator определяет, какие байтовые значения допустимы для имён колонок и как их упорядочить, а validator – для значений колонок и ключей. Если они не заданы, то Кассандра хранит значения и сравнивает их как байтовые строки (BytesType) так как, по сути, они сохраняются внутри. Вообще, в рассматриваемой СУБД доступны следующие типы данных [4]: ·       BytesType: любые байтовые строки (без валидации); ·       AsciiType: ASCII строка; ·       UTF8Type: UTF-8 строка; ·       IntegerType: число с произвольным размером; ·       Int32Type: 4-байтовое число; ·       LongType: 8-байтовое число; ·       UUIDType: UUID 1-ого или 4-ого типа; ·       TimeUUIDType: UUID 1-ого типа; ·       DateType: 8-байтовое значение метки времени; ·       BooleanType: два значения: true = 1 или false = 0; ·       FloatType: 4-байтовое число с плавающей запятой; ·       DoubleType: 8-байтовое число с плавающей запятой; ·       DecimalType: число с произвольным размером и плавающей запятой; ·       CounterColumnType: 8-байтовый счётчик.   Пространство ключей соответствует понятию схемы базы данных (database schema) в реляционной модели, а находящиеся в нем семейства столбцов – реляционной таблице. Столбцы объединяются в записи при помощи ключа (row key) в виде массива байтов, по значению которого столбцы упорядочены в пределах одной записи. В отличие от реляционных СУБД, в NoSQL модели возможна ситуация, когда разные строки содержат разное число колонок или столбцы с такими же именами, как и в других записях [4]. 
Tumblr media
Как понятия модели данных NoSQL-СУБД Кассандра соответствуют реляционной парадигме Можно сказать, конкретное значение, хранимое в Apache Cassandra, идентифицируется следующими привязками [4]: ·       к приложению или предметной области в пространстве ключей, что позволяет на одном кластере размещать данные разных приложений; ·       к запросу в рамках семейства столбцов; ·       к узлу кластера с помощью ключа, который определяет, на какие узлы попадут сохранённые колонки; ·       к атрибуту в записи с помощью имени колонки, что позволяет в одной записи хранить несколько значений. Структура данных при этом выглядит так [4]: ·       Keyspace ·       ColumnFamily ·       Row ·       Key ·       Column ·       Name ·       Value ·       Column ·       ...
Tumblr media
Модель данных Apache Cassandra
Архитектура
Apache Cassandra – это децентрализованная распределенная система, состоящая из нескольких узлов, по которым она распределяет данные. В отличие от многих других Big Data решений экосистемы Apache Hadoop (HBase, HDFS), эта СУБД не поддерживает концепцию master/slave (ведущий/ведомый), когда один из серверов является управляющим для других компонентов кластера. Для распределения элементов данных по узлам Кассандра использует последовательное хэширование, применяя хэш-алгоритм для вычисления хэш-значений ключей каждого элемента данных (имя столбца, ID строки и пр.). Диапазон всех возможных хэш-значений, т.е. пространство ключей, распределяется между узлами кластера так, что каждому элементу данных назначен свой узел, который отвечает за хранение и управление этим элементом данных [3].   Благодаря такой распределенной архитектуре, Кассандра предоставляет следующие возможности [3]: ·       распределение данных между узлами кластера прозрачно для пользователей – каждый сервер может принимать любой запрос (на чтение, запись или удаление данных), пересылая его на другой узел, если запрашиваемая информацию хранится не здесь; ·       пользователи могут сами определить необходимое количество реплик, создание и управление которыми обеспечит Cassandra; ·       настраиваемый пользователями уровень согласованности данных по каждой операции хранения и считывания; ·       высокая скорость записи (около 80-360 МБ/с на узел) – данные записываются быстрее, чем считываются за счет того, что их большая часть хранится в оперативной памяти ответственного узла, и любые обновления сперва выполняются в памяти, а только потом – в файловой системе. Чтобы избежать потери информации, все транзакции фиксируются в специальном журнале на диске. При этом, в отличие от обновления данных, записи в журналы фиксации только добавляются, что исключает задержку при вращении диска. Кроме того, если не требуется полная согласованность записей, Cassandra записывает данные в достаточное число узлов без разрешения конфликтов несоответствия, которые разрешаются только при первом считывании. ·       гибкая масштабируемость – можно построить кластер даже на сотню узлов, способный обрабатывать петабайты данных. Таким образом, отсутствие центрального узла лишает Кассандру главного недостатка, свойственного системам master/slave, в которых отказывает весь кластер при сбое главного сервера (Master Node). В кластере Cassandra все узлы равноценны между собой и, если один из них отказал, его функции возьмет на себя какой-то из оставшихся. Благодаря такой децентрализации Apache Cassandra отлично подходит для географически распределенных систем с высокой доступностью, расположенных в разных датацентрах. Однако, при всех преимуществах такой гибко масштабируемой архитектуры, она обусловливает особенности операций чтения и записи, а также накладывает ряд существенных ограничений на использование этой СУБД в реальных Big Data проектах.
Tumblr media
Кластерная архитектура Apache Cassandra О ключевых возможностях, достоинствах и недостатках Apache Cassandra, а также примерах практического применения этой СУБД класса NoSQL в реальных Big Data проектах мы расскажем в отдельной статье.   Источники 1.       https://ru.wikipedia.org/wiki/Apache_Cassandra 2.       https://eax.me/cassandra/ 3.       https://www.ibm.com/developerworks/ru/library/os-apache-cassandra/ 4.       https://ru.bmstu.wiki/Apache_Cassandra Read the full article
0 notes