Установка и настройка apache spark на windows

Обновлено: 07.07.2024

Эта статья представляет собой краткое руководство по установке Apache Spark для одного узла и использованию библиотеки Python Spark PySpark.

  • Версия Hadoop: 3.1.0
  • Apache Kafka Версия: 1.1.1
  • Операционная система: Ubuntu 16.04
  • Версия Java: Java 8

Apache Spark требует Java. Чтобы убедиться, что Java установлена, сначала обновите операционную систему, а затем попробуйте установить ее:

Для начала нам нужно создать каталог для Apache Spark.

Затем нам нужно скачать пакет apache spark binaries.

Далее нам нужно распаковать файлы apache spark в каталог / opt / spark

Когда Spark запускает задания, он переносит свои файлы JAR в HDFS, чтобы они были доступны всем работающим машинам. Эти файлы являются большими накладными расходами на небольших заданиях, поэтому я упаковал их, скопировал их в HDFS и сказал Spark, что больше не нужно их копировать.

После копирования файлов мы должны указать Spark игнорировать копирование файлов JAR из конфигурационного файла по умолчанию:

Добавьте следующие строки:

В этой статье мы настроим Apache Spark для работы на одном узле, так что это будет только localhost:

Убедитесь, что он содержит только значение localhost

Перед запуском сервиса мы должны открыть файл .bashrc с помощью gedit

И добавьте следующие строки

Теперь нам нужно запустить службы Apache Spark:

Ubuntu 16.04 поставляется с предустановленным Python 3 и Python 2. Чтобы убедиться, что наши версии обновлены, мы должны обновить и обновить систему с помощью apt-get (упомянутой в разделе предварительных требований):

Мы можем проверить версию Python 3, которая установлена ​​в системе, набрав:

Он должен возвращать релиз Python (пример: Python 3.5.2)

Чтобы управлять программными пакетами для Python, мы должны установить утилиту pip:

Необходимо установить еще несколько пакетов и инструментов разработки, чтобы обеспечить надежную настройку для нашей среды программирования.

Сначала нам нужно установить модуль venv, который позволит нам создавать виртуальные среды:

Далее мы должны создать каталог для нашей среды

Теперь нам нужно перейти в этот каталог и создать среду (все файлы среды будут созданы внутри каталога, который мы назвали my_env):

Мы закончили, мы можем проверить файлы среды, созданные с помощью ls my_env

Чтобы использовать эту среду, вам необходимо активировать ее:

Сначала нам нужно открыть файл .bashrc

И добавьте следующие строки:

Если на компьютере установлен Apache Spark, нам не нужно устанавливать библиотеку pyspark в нашу среду разработки. Нам нужно установить библиотеку findspark, которая отвечает за поиск библиотеки pyspark, установленной вместе с apache Spark.

В каждом файле скрипта Python мы должны добавить следующие строки:

Следующий скрипт предназначен для чтения из файла, хранящегося в hdfs


Apache Spark объясняется как «быстрый и общий механизм для крупномасштабной обработки данных». Однако это даже не начинает инкапсулировать причину, по которой он стал таким выдающимся игроком в пространстве больших данных. Apache Spark является платформой распределенных вычислений, и ее внедрение компаниями, работающими с большими данными, набирает популярность.

Архитектура искры выглядит следующим образом:


Spark - это механизм распределенной обработки, но у него нет собственного распределенного хранилища и диспетчера кластеров для ресурсов. Он работает поверх стандартного диспетчера ресурсов кластера и распределенного хранилища.

Ядро Spark состоит из двух частей:

  • Основные API: Неструктурированные API (RDD), Структурированные API (DataFrames, Datasets). Доступно в Scala, Python, Java и R.
  • Compute Engine: управление памятью, планирование задач, восстановление после сбоев, взаимодействие с Cluster Manager.

Примечание. В конце статьи мы увидим основные реализации API в Java.

Вне Базовых API Spark предоставляет:

  • Spark SQL: взаимодействовать со структурированными данными с помощью SQL-запросов.
  • Потоковая передача: использование и обработка непрерывного потока данных.
  • MLlib: Библиотека машинного обучения. Тем не менее, я бы не рекомендовал обучать модели глубокого обучения здесь.
  • GraphX: типичный алгоритм обработки графиков.

Все вышеперечисленные четыре напрямую зависят от API ядра Spark для распределенных вычислений.

Преимущества Spark

  • Spark предоставляет унифицированную платформу для пакетной обработки, структурированной обработки данных, потоковой передачи и многого другого.
  • По сравнению с Hadoop-сокращением карты код искры намного проще в написании и использовании.
  • Самая важная особенность Spark - это абстракция аспекта параллельного программирования. Spark core абстрагирует сложности распределенного хранения, вычислений и параллельного программирования.

Одним из основных вариантов использования Apache Spark является крупномасштабная обработка данных. Мы создаем программы и выполняем их на искровых кластерах.

Выполнение программы в кластере

Есть в основном два метода для выполнения программ на кластере искр:

Большая часть процесса разработки происходит на интерактивных клиентах, но когда нам нужно запустить наше приложение в производство, мы используем подход «Подать заявку».



Лента новостей - потоковая работа. Ежедневная аналитика YouTube - Batch Job

Как для продолжительного потокового задания, так и для периодического пакетного задания мы упаковываем наше приложение и отправляем его в кластер Spark для выполнения.


Spark, механизм распределенной обработки, следует архитектуре ведущий-ведомый. В искровой терминологии мастер являетсяВодительи рабыисполнители,


Водитель несет ответственность за:

  1. Анализ
  2. Раздача.
  3. Мониторинг.
  4. Планирование.
  5. Сохранение всей необходимой информации в течение всего срока службы искрового процесса.

Исполнители несут ответственность только за выполнение части кода, назначенной им водителем, и возвращение статуса водителю.

Каждый искровой процесс будет иметь отдельного драйвера и эксклюзивных исполнителей.

Режимы исполнения

  1. Режим клиента:Драйвером является локальная виртуальная машина, куда вы отправляете свою заявку. По умолчанию spark подает все приложения в режиме клиента. Поскольку драйвер является главным узлом во всем процессе зажигания, при настройке производства это не рекомендуется. Для отладки имеет смысл использовать режим клиента.
  2. Кластерный режим:Водитель является одним из исполнителей в кластере. В spark-submit вы можете передать аргумент следующим образом:

Диспетчер кластерных ресурсов


Yarn и Mesos - это часто используемый менеджер кластеров.

Kubernetes - это контейнерный оркестр общего назначения.

Примечание: Искра на Кубернетес не готова к производству.

Yarn - самый популярный менеджер ресурсов для spark, давайте посмотрим, как это работает:

В приложении клиентского режима драйвер - наша локальная виртуальная машина, для запуска приложения spark:

Шаг 1:Как только драйвер запускает сеанс искры, запрос отправляется в Yarn для создания приложения пряжи.

Шаг 2:Менеджер ресурсов пряжи создает мастер приложений. Для клиентского режима AM действует как средство запуска исполнителя.

Шаг 3:AM обратился бы к менеджеру ресурсов Yarn, чтобы запросить дополнительные контейнеры.

Шаг 4:Resource Manager будет выделять новые контейнеры, а AM запускает исполнителей в каждом контейнере. После этого исполнители напрямую общаются с водителем.


Примечание. В режиме кластера драйвер запускается в режиме AM.

Исполнитель и настройка памяти

Аппаратное обеспечение - 6 узлов, каждый узел 16 ядер, 64 ГБ ОЗУ

Давайте начнем с количества ядер. Количество ядер представляет собой параллельную задачу, которую может выполнить исполнитель. Исследования показали, что любое приложение, имеющее более 5 одновременных задач, приводит к плохому шоу Следовательно, я бы предложил придерживаться 5.

Примечание. Приведенное выше число связано с производительностью исполнителя, а не с количеством ядер, имеющихся в системе. Следовательно, он останется таким же и для 32-ядерных систем.

1 ядро ​​Требуется 1 ГБ оперативной памяти для демонов ОС и Hadoop. Следовательно, у нас осталось 63 ГБ ОЗУ и 15 ядер.

Для 15 ядер у нас может быть 3 исполнителя на узел. Это дает нам 18 исполнителей в общей сложности. Для AM Container требуется 1 исполнитель. Следовательно, мы можем получить 17 исполнителей.

Выходя в память, мы получаем 63/3 = 21 ГБ на исполнителя. Однако при вычислении запроса на полную память необходимо учитывать небольшие накладные расходы.

Следовательно, объем памяти уменьшается примерно до 19 ГБ.

Следовательно система приходит к:

Примечание: если нам требуется меньше памяти, мы можем уменьшить количество ядер, чтобы увеличить количество исполнителей.

Теперь мы рассмотрим некоторые основные API-интерфейсы, которые предоставляет spark. Spark нужна структура данных для хранения данных. У нас есть три варианта: RDD, DataFrame и Dataset. Начиная с Spark 2.0 рекомендуется использовать только набор данных и DataFrame. Эти два внутренне компилируются в сам RDD.

Эти три являются гибким, распределенным, разделенным и неизменным сбором данных.


Задача:Самая маленькая единица работы в Spark и выполняется исполнителем.

Набор данных предлагает два типа действий:

  • Трансформации:Создает новый набор данных из существующего. Это лениво, и данные остаются распределенными.
  • Действие:Действие возвращает данные драйверу, не распределенные по природе. Действие на наборе данных запускает работу.

Перемешать и сортировать:Повторное разбиение набора данных для выполнения действий с ним. Это абстракция в искре, и нам не нужно писать код для нее. Эта деятельность требует нового этапа.

1) горит, geq, leq, gt, lt

горит: создает столбец литерального значения. Может использоваться для сравнения с другими столбцами.

geq (больше чем равно), leq (меньше чем равно), gt (больше чем), lt (меньше чем): используется для сравнения со значением другого столбца. Например:

2) присоединиться

Spark позволяет нам присоединяться к наборам данных различными способами. Попробую объяснить на примере примера

Результат выглядит так:

3) союз

Функция Spark union позволяет нам объединять два набора данных. Наборы данных должны иметь одну и ту же схему.

4) окно

Одна из основных функций в Spark. Это позволяет вычислить возвращаемое значение для каждой входной строки таблицы на основе группы строк, называемойРамка,

Spark предоставляет API для падающего окна, окна надежды, скользящего окна и отложенного окна.

Мы используем его для ранжирования, сумм, старых окон и т. Д. Некоторые из вариантов использования:

Другие функции, такие какзапаздывание,вестии многое другое позволит вам выполнять другие операции, которые позволяют выполнять сложную аналитику по наборам данных.

Однако, если вам все еще нужно выполнять гораздо более сложные операции над наборами данных, вы можете использовать UDF. Пример использования UDF:

Примечание. Использование UDF должно быть последним средством, поскольку они не оптимизированы для Spark; они могли бы взятьДолгое времядля казней. Желательно использовать собственные функции искры над UDF.

Это только вершина айсберга для Apache Spark. Его утилиты распространяются в различных областях, не ограничиваясь анализом данных. Смотреть это место для большего.

Apache Spark is a framework used in cluster computing environments for analyzing big data. This platform became widely popular due to its ease of use and the improved data processing speeds over Hadoop.

Apache Spark is able to distribute a workload across a group of computers in a cluster to more effectively process large sets of data. This open-source engine supports a wide array of programming languages. This includes Java, Scala, Python, and R.

In this tutorial, you will learn how to install Spark on an Ubuntu machine. The guide will show you how to start a master and slave server and how to load Scala and Python shells. It also provides the most important Spark commands.

Tutorial on how to install Spark on an Ubuntu machine.

  • An Ubuntu system.
  • Access to a terminal or command line.
  • A user with sudo or root permissions.

Install Packages Required for Spark

Before downloading and setting up Spark, you need to install necessary dependencies. This step includes installing the following packages:

Open a terminal window and run the following command to install all three packages at once:

You will see which packages will be installed.

Terminal output when installing Spark dependencies.

Once the process completes, verify the installed dependencies by running these commands:

Terminal output when verifying Java, Git and Scala versions.

The output prints the versions if the installation completed successfully for all packages.

Download and Set Up Spark on Ubuntu

Now, you need to download the version of Spark you want form their website. We will go for Spark 3.0.1 with Hadoop 2.7 as it is the latest version at the time of writing this article.

Use the wget command and the direct link to download the Spark archive:

When the download completes, you will see the saved message.

Output when saving Spark to your Ubuntu machine.

Note: If the URL does not work, please go to the Apache Spark download page to check for the latest version. Remember to replace the Spark version number in the subsequent commands if you change the download URL.

Now, extract the saved archive using tar:

Let the process complete. The output shows the files that are being unpacked from the archive.

Finally, move the unpacked directory spark-3.0.1-bin-hadoop2.7 to the opt/spark directory.

Use the mv command to do so:

The terminal returns no response if it successfully moves the directory. If you mistype the name, you will get a message similar to:

Configure Spark Environment

Before starting a master server, you need to configure environment variables. There are a few Spark home paths you need to add to the user profile.

Use the echo command to add these three lines to .profile:

You can also add the export paths by editing the .profile file in the editor of your choice, such as nano or vim.

For example, to use nano, enter:

When the profile loads, scroll to the bottom of the file.

Nano editor with the profile file open to add Spark variables.

Then, add these three lines:

Exit and save changes when prompted.

When you finish adding the paths, load the .profile file in the command line by typing:

Start Standalone Spark Master Server

Now that you have completed configuring your environment for Spark, you can start a master server.

In the terminal, type:

To view the Spark Web user interface, open a web browser and enter the localhost IP address on port 8080.

The page shows your Spark URL, status information for workers, hardware resource utilization, etc.

The home page of the Spark Web UI.

The URL for Spark Master is the name of your device on port 8080. In our case, this is ubuntu1:8080. So, there are three possible ways to load Spark Master’s Web UI:

  1. 127.0.0.1:8080
  2. localhost:8080
  3. deviceName:8080

Note: Learn how to automate the deployment of Spark clusters on Ubuntu servers by reading our Automated Deployment Of Spark Cluster On Bare Metal Cloud article.

Start Spark Slave Server (Start a Worker Process)

In this single-server, standalone setup, we will start one slave server along with the master server.

To do so, run the following command in this format:

The master in the command can be an IP or hostname.

In our case it is ubuntu1 :

The terminal output when starting a slave server.

Now that a worker is up and running, if you reload Spark Master’s Web UI, you should see it on the list:

Spark Web UI with one slave worker started.

Specify Resource Allocation for Workers

The default setting when starting a worker on a machine is to use all available CPU cores. You can specify the number of cores by passing the -c flag to the start-slave command.

For example, to start a worker and assign only one CPU core to it, enter this command:

Reload Spark Master’s Web UI to confirm the worker’s configuration.

Slave server CPU cores configuration in Web UI.

Similarly, you can assign a specific amount of memory when starting a worker. The default setting is to use whatever amount of RAM your machine has, minus 1GB.

To start a worker and assign it a specific amount of memory, add the -m option and a number. For gigabytes, use G and for megabytes, use M .

For example, to start a worker with 512MB of memory, enter this command:

Reload the Spark Master Web UI to view the worker’s status and confirm the configuration.

Spark slave server RAM configuration on Web UI.

Test Spark Shell

After you finish the configuration and start the master and slave server, test if the Spark shell works.

Load the shell by entering:

You should get a screen with notifications and Spark information. Scala is the default interface, so that shell loads when you run spark-shell.

The ending of the output looks like this for the version we are using at the time of writing this guide:

Terminal showing the screen when you launch a Spark shell on Ubuntu.

Type :q and press Enter to exit Scala.

Test Python in Spark

If you do not want to use the default Scala interface, you can switch to Python.

Make sure you quit Scala and then run this command:

The resulting output looks similar to the previous one. Towards the bottom, you will see the version of Python.

The terminal showing the screen when pyspark shell is launched.

To exit this shell, type quit() and hit Enter.

Basic Commands to Start and Stop Master Server and Workers

Below are the basic commands for starting and stopping the Apache Spark master server and workers. Since this setup is only for one machine, the scripts you run default to the localhost.

To start a master server instance on the current machine, run the command we used earlier in the guide:

To stop the master instance started by executing the script above, run:

To stop a running worker process, enter this command:

The Spark Master page, in this case, shows the worker status as DEAD.

Spark Web UI showing a worker status: dead.

You can start both master and server instances by using the start-all command:

Similarly, you can stop all instances by using the following command:

This tutorial showed you how to install Spark on an Ubuntu machine, as well as the necessary dependencies.

The setup in this guide enables you to perform basic tests before you start configuring a Spark cluster and performing advanced actions.

Our suggestion is to also learn more about what Spark DataFrame is, the features, how to use Spark DataFrame when collecting data and how to create a Spark DataFrame.

Apache Spark is an open-source framework that processes large volumes of stream data from multiple sources. Spark is used in distributed computing with machine learning applications, data analytics, and graph-parallel processing.

This guide will show you how to install Apache Spark on Windows 10 and test the installation.

tutorial on installing apache spark on windows

  • A system running Windows 10
  • A user account with administrator privileges (required to install software, modify file permissions, and modify system PATH)
  • Command Prompt or Powershell
  • A tool to extract .tar files, such as 7-Zip

Install Apache Spark on Windows

Installing Apache Spark on Windows 10 may seem complicated to novice users, but this simple tutorial will have you up and running. If you already have Java 8 and Python 3 installed, you can skip the first two steps.

Step 1: Install Java 8

Apache Spark requires Java 8. You can check to see if Java is installed using the command prompt.

Open the command line by clicking Start > type cmd > click Command Prompt.

Type the following command in the command prompt:

If Java is installed, it will respond with the following output:

Windows CLI output for Java version.

Your version may be different. The second digit is the Java version – in this case, Java 8.

If you don’t have Java installed:

Java download page in a browser

2. Click the Java Download button and save the file to a location of your choice.

3. Once the download finishes double-click the file to install Java.

Step 2: Install Python

2. Mouse over the Download menu option and click Python 3.8.3. 3.8.3 is the latest version at the time of writing the article.

3. Once the download finishes, run the file.

Python download page for version 3.8.3

4. Near the bottom of the first setup dialog box, check off Add Python 3.8 to PATH. Leave the other box checked.

5. Next, click Customize installation.

Python wizard 3.8.3, step to add Python to PATH

6. You can leave all boxes checked at this step, or you can uncheck the options you do not want.

7. Click Next.

8. Select the box Install for all users and leave other boxes as they are.

9. Under Customize install location, click Browse and navigate to the C drive. Add a new folder and name it Python.

10. Select that folder and click OK.

Python installation, advanced options step

11. Click Install, and let the installation complete.

12. When the installation completes, click the Disable path length limit option at the bottom and then click Close.

13. If you have a command prompt open, restart it. Verify the installation by checking the version of Python:

The output should print Python 3.8.3 .

Note: For detailed instructions on how to install Python 3 on Windows or how to troubleshoot potential issues, refer to our Install Python 3 on Windows guide.

Step 3: Download Apache Spark

2. Under the Download Apache Spark heading, there are two drop-down menus. Use the current non-preview version.

  • In our case, in Choose a Spark releasedrop-down menu select 2.4.5 (Feb 05 2020).
  • In the second drop-down Choose a package type, leave the selection Pre-built for Apache Hadoop 2.7.

3. Click the spark-2.4.5-bin-hadoop2.7.tgz link.

Apache Spark download page.

4. A page with a list of mirrors loads where you can see different servers to download from. Pick any from the list and save the file to your Downloads folder.

Step 4: Verify Spark Software File

1. Verify the integrity of your download by checking the checksum of the file. This ensures you are working with unaltered, uncorrupted software.

2. Navigate back to the Spark Download page and open the Checksum link, preferably in a new tab.

3. Next, open a command line and enter the following command:

4. Change the username to your username. The system displays a long alphanumeric code, along with the message Certutil: -hashfile completed successfully .

Checksum output for the Spark installation file.

5. Compare the code to the one you opened in a new browser tab. If they match, your download file is uncorrupted.

Step 5: Install Apache Spark

Installing Apache Spark involves extracting the downloaded file to the desired location.

1. Create a new folder named Spark in the root of your C: drive. From a command line, enter the following:

2. In Explorer, locate the Spark file you downloaded.

3. Right-click the file and extract it to C:\Spark using the tool you have on your system (e.g., 7-Zip).

4. Now, your C:\Spark folder has a new folder spark-2.4.5-bin-hadoop2.7 with the necessary files inside.

Step 6: Add winutils.exe File

Download the winutils.exe file for the underlying Hadoop version for the Spark installation you downloaded.

Winutils download page

2. Find the Download button on the right side to download the file.

3. Now, create new folders Hadoop and bin on C: using Windows Explorer or the Command Prompt.

4. Copy the winutils.exe file from the Downloads folder to C:\hadoop\bin.

Step 7: Configure Environment Variables

Configuring environment variables in Windows adds the Spark and Hadoop locations to your system PATH. It allows you to run the Spark shell directly from a command prompt window.

1. Click Start and type environment.

2. Select the result labeled Edit the system environment variables.

3. A System Properties dialog box appears. In the lower-right corner, click Environment Variables and then click New in the next window.

Add new environment variable in Windows.

4. For Variable Name type SPARK_HOME.

5. For Variable Value type C:\Spark\spark-2.4.5-bin-hadoop2.7 and click OK. If you changed the folder path, use that one instead.

Adding Spark home variable path in Windows.

6. In the top box, click the Path entry, then click Edit. Be careful with editing the system path. Avoid deleting any entries already on the list.

Edit the path variable to add Spark home.

7. You should see a box with entries on the left. On the right, click New.

8. The system highlights a new line. Enter the path to the Spark folder C:\Spark\spark-2.4.5-bin-hadoop2.7\bin. We recommend using %SPARK_HOME%\bin to avoid possible issues with the path.

Adding the Spark home to the path Windows variable.

9. Repeat this process for Hadoop and Java.

  • For Hadoop, the variable name is HADOOP_HOME and for the value use the path of the folder you created earlier: C:\hadoop. Add C:\hadoop\bin to the Path variable field, but we recommend using %HADOOP_HOME%\bin.
  • For Java, the variable name is JAVA_HOME and for the value use the path to your Java JDK directory (in our case it’s C:\Program Files\Java\jdk1.8.0_251).

10. Click OK to close all open windows.

Note: Star by restarting the Command Prompt to apply changes. If that doesn't work, you will need to reboot the system.

Step 8: Launch Spark

1. Open a new command-prompt window using the right-click and Run as administrator:

2. To start Spark, enter:

If you set the environment path correctly, you can type spark-shell to launch Spark.

3. The system should display several lines indicating the status of the application. You may get a Java pop-up. Select Allow access to continue.

Finally, the Spark logo appears, and the prompt displays the Scala shell.

Scala shell after launching apacheSpark in windows

5. You can replace localhost with the name of your system.

6. You should see an Apache Spark shell Web UI. The example below shows the Executors page.

Spark Windows Executors page Web UI

7. To exit Spark and close the Scala shell, press ctrl-d in the command-prompt window.

Note: If you installed Python, you can run Spark using Python with this command:


Exit using quit().

Test Spark

In this example, we will launch the Spark shell and use Scala to read the contents of a file. You can use an existing file, such as the README file in the Spark directory, or you can create your own. We created pnaptest with some text.

1. Open a command-prompt window and navigate to the folder with the file you want to use and launch the Spark shell.

2. First, state a variable to use in the Spark context with the name of the file. Remember to add the file extension if there is any.

3. The output shows an RDD is created. Then, we can view the file contents by using this command to call an action:

Spark Scala test action with reading a file.

This command instructs Spark to print 11 lines from the file you specified. To perform an action on this file (value x), add another value y, and do a map transformation.

4. For example, you can print the characters in reverse with this command:

5. The system creates a child RDD in relation to the first one. Then, specify how many lines you want to print from the value y:

Spark scala action to put the characters of a file in reverse.

The output prints 11 lines of the pnaptest file in the reverse order.

When done, exit the shell using ctrl-d .

You should now have a working installation of Apache Spark on Windows 10 with all dependencies installed. Get started running an instance of Spark in your Windows environment.

Our suggestion is to also learn more about what Spark DataFrame is, the features, and how to use Spark DataFrame when collecting data.

Читайте также: