- Как установить ElasticSearch 7
- Установка Elasticsearch на Linux/Ubuntu
- Настройка Elasticsearch
- Удалённый доступ
- Установка ElasticSearch в Docker
- Установка Elasticsearch в Vagrant
- Установка Elasticsearch на Windows 10
- Резюме
- Subscribe to Блог php программиста: статьи по PHP, JavaScript, MySql
- Install elasticsearch windows 10
- Download and install the .zip packageedit
- Enable automatic creation of system indicesedit
- Running Elasticsearch from the command lineedit
- Configuring Elasticsearch on the command lineedit
- Checking that Elasticsearch is runningedit
- Installing Elasticsearch as a Service on Windowsedit
- Customizing service settingsedit
- Directory layout of .zip archiveedit
- Next stepsedit
Как установить ElasticSearch 7
Ввиду того, что в будущем я планирую выпустить несколько статьей, основанных на работе с ElasticSearch, в этой статье я решил показать самые распространённые варианты его установки. В этой статье собраны все варианты установки Elasticsearch 7: на Ubuntu 18.10, Windows 10, Docker, Vagrant Homestead. Многие ищут статьи на тему быстрого старта по работе с ES, однако, любой старт начинается именно с установки^^.
Установка Elasticsearch на Linux/Ubuntu
Для того, чтобы установить Elasticsearch на Ubuntu, нужно открыть страницу их офф.документации.
При установке я использую Ubuntu 18.10, но, даже, если у вас другая версия, то процесс не будет иметь кардинальных отличий.
Для работы Elasticsearch на Linux, нужно сначала установить Java 8 версии, или более новую. Для этого, выполните код:
И получите окно вывод примерно с таким содержимым:
После чего, приступим к установке самого Elasticsearch.
Сначала нужно выполнить:
В результате чего, эта команда должна вернуть ответ: OK .
Этой командой мы установим ElasticSearch 7 версии. Если вам нужна какая-то конкретная версия, или более старая версия, то измените версию на нужную, вместо 7.x
После чего, выполним следующие команды:
После выполнения этих команд, Elasticsearch будет установлен. Однако, он не запустится сразу после установки, запустить его придётся вручную, выполнив:
И теперь, для того, чтобы удостовериться, что Elasticsearch успешно установлен, можем отправить HTTP-запрос на 9200 порт, на котором висит ES. Запрос отправим с помощью curl:
И вы должны увидеть что-то вроде этого:
Сам запуск Elastsearch займёт где-то 5-10 секунд. Потому, если вы увидете сообщение curl: (7) Failed to connect to localhost port 9200: Connection refused , подождите несколько секунд, и повторите свой запрос.
Если эта ошибка не пропадает, то это означает, что сервис не удаётся запустить. Вероятно, это из-за недостатка оперативной памяти. Для того, чтобы посмотреть подробный лог Elasticsearch, можете выполнить команду: sudo journalctl -u elasticsearch
Но, уверен, что у вас всё запустилось, мои поздравления!
Настройка Elasticsearch
Если вам интересно, в какой директории Elasticsearch хранит данные, то они находятся в директории /var/lib/elasticsearch , конфигурационные данные в /etc/elasticsearch , а настройки Java для Elasticsearch расположены в файле /etc/default/elasticsearch .
По умолчанию Elasticsearch настроен только для локального доступа, для доступа только изнутри текущей системы, в которую он установлен. Вы не можете достучаться к нему удалённо. И, если клиент подключаемый к Elasticsearch запущен на том же сервере, что и сам Elasticsearch, вам не нужно менять конфигурационные файлы. Если это не так, то есть опция настройки удалённого доступа к Elasticsearch.
Удалённый доступ
Elasticsearch не имеет встроенной системы аутентификации, потому, если вы разрешите удалённый доступ, то получить информацию от Elasticsearch может кто угодно, кто имеет возможность выполнять HTTP-запросы к API. Если вы хотите разрешить удалённый доступ к серверу Elasticsearch, вам нужно настроить файрвол, и разрешить доступ к 9200 порту Elasticsearch сервера только для доверенных клиентов.
В Ubuntu стандартно установлено ПО по настройке файрвол UFW. По умолчанию, UFW установлен в систему, но не включён. Но, перед его включением, добавим одно правило для разрешения входящего трафика по SSH:
Теперь, разрешим удалённый доступ для доверенного IP адреса:
Вместо x.x.x.x напишите ваш реальный IP адрес. В моём случае, команда будет иметь вид sudo ufw allow from 134.249.138.171 to any port 9200
Если вы занимаетесь локальной разработкой, то можете не ограничивать доступ по конкретному IP, для этого, вместо предыдущей команды нужно выполнить: sudo ufw allow to any port 9200
Теперь можно включать UFW:
И последнее, проверим статус файрвола:
Где мы должны увидеть добавленное правило:
Теперь, когда файрвол настроен должным образом, следующим шагом будет редактирование конфигов Elasticsearch , и разрешение внешних подключения к Elasticsearch.
Для этого, откроем конфигурационный файл elasticsearch.yml :
Где нужно найти строку, которая содержит network.host , её нужно раскомментировать, и изменить значение на 0.0.0.0 , раскомментировать http.port и добавить некоторые параметры, чтобы конфигурация имела вид:
Для того, чтобы выйти из редактирования файла в редакторе nano , нужно нажать CTRL+C , напечатав символ согласия y .
Теперь, перезагрузим Elastisearch, чтобы изменения вступили в силу:
И это всё. Теперь у вас есть возможность подключения к Elastisearch удалённо.
И теперь, после всего проделанного, вы знаете, как настроить удалённое подключение к Elasticsearch. Теперь вы можете подключаться из любого места, и любого HTTP-клиента.
В этом пункте было показано, как установить Elasticsearch в Ubuntu 18.10. Теперь вы можете посетить офф.документацию для начала работы и более детального изучения основ работы с Elasticsearch.
Установка ElasticSearch в Docker
Если вы ещё не знакомы к Докером, то на сайте есть отличная статья по работе с ним.
Для начала, нужно скачать образ с предустановленным Elasticsearch:
Теперь, когда скачивание дойдёт до конца, его можно запустить командой:
В результате чего, Elasticsearch станет доступен по адресу localhost:9200.
Установка Elasticsearch в Vagrant
Для того, чтобы установить Elasticsearch в Vagrant (Homestead) нужно добавить опцию elasticsearch в файле Homestead.yaml , указав нужную поддерживаемую версию. При создании виртуальной машины, по умолчанию, будет создан кластер под названием homestead .
Вы не должны предоставлять Elasticsearch больше, чем половина вашей доступной оперативной памяти, потому, убедитесь, что ваш Homestead настроен в соответствии этому замечанию.
Для того, чтобы прокинуть порты для удалённого доступа, нужно дополнить Homestead.yaml:
И, аналогично, как описывалось в секции настройки удалённого доступа, нужно прописать в файл /etc/elasticsearch/elasticsearch.yml новые параметры, разрешив удалённый доступ.
Будьте внимательны, и не оставляйте дублирующих параметров. Т.е., удалите старые, по-умолчанию заданные параметры transport.host , http.port , и т.д.
После чего, удалённый доступ заработает. Учтите, что в этом случае, доступ к Elasticsearch будет осуществляться не по адресу localhost:9200, а по параметру IP, указанному в Homestead.yml. В моём случае, это 192.168.10.10:9200.
Установка Elasticsearch на Windows 10
Для установки Elasticsearch на Windows, перейдите на страницу и выберите нужную версия для скачивания (я предпочитаю *.msi версию).
Используя графический интерфейс, установите настройки: директории для хранения данных, логов, и конфигов, или же, используйте настройки по-умолчанию.
Потом, выберите, установка «as a service» или установка с ручной настройкой, если нужно. Когда установлено «as a service», вы можете так же настроить Windows аккаунт для запуска службы, а так же настроить поведение при старте вашей ОС (запускать ли автоматически и т.д.).
Основные системные настройки производятся на последней странице: указывается имя кластера, имя, размер ОЗУ и настройки сети.
На следующей странице выбора плагинов можно ничего не выбирать, осталось подтвердить начало установки, нажав на кнопку Install .
В конце установки, на вашем компьютере запустится служба Elasticsearch, и убедиться в этом можно, перейдя по адресу localhost:9200.
Резюме
В этой статье я показал, как устанавливать Elasticsearch 7 под разные операционные системы: Ubuntu и Windows. Так же, была рассмотрена установка, запуск и настройка Elasticsearch на Docker и Homestead Vagrant. Это была первая статья по работе с Elasticsearch, для того, чтобы в будущем показать подробные примеры по работе с ним.
Subscribe to Блог php программиста: статьи по PHP, JavaScript, MySql
Get the latest posts delivered right to your inbox
Install elasticsearch windows 10
Elasticsearch can be installed on Windows using the Windows .zip archive. This comes with a elasticsearch-service.bat command which will setup Elasticsearch to run as a service.
Elasticsearch has historically been installed on Windows using the .zip archive. An MSI installer package is available that provides the easiest getting started experience for Windows. You can continue using the .zip approach if you prefer.
This package contains both free and subscription features. Start a 30-day trial to try out all of the features.
On Windows the Elasticsearch machine learning feature requires the Microsoft Universal C Runtime library. This is built into Windows 10, Windows Server 2016 and more recent versions of Windows. For older versions of Windows it can be installed via Windows Update, or from a separate download. If you cannot install the Microsoft Universal C Runtime library you can still use the rest of Elasticsearch if you disable the machine learning feature.
The latest stable version of Elasticsearch can be found on the Download Elasticsearch page. Other versions can be found on the Past Releases page.
Elasticsearch includes a bundled version of OpenJDK from the JDK maintainers (GPLv2+CE). To use your own version of Java, see the JVM version requirements
Download and install the .zip packageedit
Unzip it with your favourite unzip tool. This will create a folder called elasticsearch-7.12.0 , which we will refer to as %ES_HOME% . In a terminal window, cd to the %ES_HOME% directory, for instance:
Enable automatic creation of system indicesedit
Some commercial features automatically create indices within Elasticsearch. By default, Elasticsearch is configured to allow automatic index creation, and no additional steps are required. However, if you have disabled automatic index creation in Elasticsearch, you must configure action.auto_create_index in elasticsearch.yml to allow the commercial features to create the following indices:
If you are using Logstash or Beats then you will most likely require additional index names in your action.auto_create_index setting, and the exact value will depend on your local configuration. If you are unsure of the correct value for your environment, you may consider setting the value to * which will allow automatic creation of all indices.
Running Elasticsearch from the command lineedit
Elasticsearch can be started from the command line as follows:
If you have password-protected the Elasticsearch keystore, you will be prompted to enter the keystore’s password. See Secure settings for more details.
By default, Elasticsearch runs in the foreground, prints its logs to STDOUT , and can be stopped by pressing Ctrl-C .
Configuring Elasticsearch on the command lineedit
Elasticsearch loads its configuration from the %ES_HOME%\config\elasticsearch.yml file by default. The format of this config file is explained in Configuring Elasticsearch.
Any settings that can be specified in the config file can also be specified on the command line, using the -E syntax as follows:
Values that contain spaces must be surrounded with quotes. For instance -Epath.logs=»C:\My Logs\logs» .
Typically, any cluster-wide settings (like cluster.name ) should be added to the elasticsearch.yml config file, while any node-specific settings such as node.name could be specified on the command line.
Checking that Elasticsearch is runningedit
You can test that your Elasticsearch node is running by sending an HTTP request to port 9200 on localhost :
which should give you a response something like this:
Installing Elasticsearch as a Service on Windowsedit
Elasticsearch can be installed as a service to run in the background or start automatically at boot time without any user interaction. This can be achieved through the elasticsearch-service.bat script in the bin\ folder which allows one to install, remove, manage or configure the service and potentially start and stop the service, all from the command-line.
The script requires one parameter (the command to execute) followed by an optional one indicating the service id (useful when installing multiple Elasticsearch services).
The commands available are:
Install Elasticsearch as a service
Remove the installed Elasticsearch service (and stop the service if started)
Start the Elasticsearch service (if installed)
Stop the Elasticsearch service (if started)
Start a GUI for managing the installed service
The name of the service and the value of ES_JAVA_HOME will be made available during install:
While a JRE can be used for the Elasticsearch service, due to its use of a client VM (as opposed to a server JVM which offers better performance for long-running applications) its usage is discouraged and a warning will be issued.
The system environment variable ES_JAVA_HOME should be set to the path to the JDK installation that you want the service to use. If you upgrade the JDK, you are not required to the reinstall the service but you must set the value of the system environment variable ES_JAVA_HOME to the path to the new JDK installation. However, upgrading across JVM types (e.g. JRE versus SE) is not supported, and does require the service to be reinstalled.
Customizing service settingsedit
The Elasticsearch service can be configured prior to installation by setting the following environment variables (either using the set command from the command line, or through the System Properties->Environment Variables GUI).
A unique identifier for the service. Useful if installing multiple instances on the same machine. Defaults to elasticsearch-service-x64 .
The user to run as, defaults to the local system account.
The password for the user specified in %SERVICE_USERNAME% .
The name of the service. Defaults to Elasticsearch %SERVICE_ID% .
The description of the service. Defaults to Elasticsearch Windows Service — https://elastic.co .
The installation directory of the desired JVM to run the service under.
Service log directory, defaults to %ES_HOME%\logs . Note that this does not control the path for the Elasticsearch logs; the path for these is set via the setting path.logs in the elasticsearch.yml configuration file, or on the command line.
Configuration file directory (which needs to include elasticsearch.yml , jvm.options , and log4j2.properties files), defaults to %ES_HOME%\config .
Any additional JVM system properties you may want to apply.
Startup mode for the service. Can be either auto or manual (default).
The timeout in seconds that procrun waits for service to exit gracefully. Defaults to 0 .
At its core, elasticsearch-service.bat relies on Apache Commons Daemon project to install the service. Environment variables set prior to the service installation are copied and will be used during the service lifecycle. This means any changes made to them after the installation will not be picked up unless the service is reinstalled.
By default, Elasticsearch automatically sizes JVM heap based on a node’s roles and total memory. We recommend this default sizing for most production environments. If needed, you can override default sizing by manually setting the heap size.
When installing Elasticsearch on Windows as a service for the first time or running Elasticsearch from the command line, you can manually set the heap size as described in Setting JVM heap size. To resize the heap for an already installed service, use the service manager: bin\elasticsearch-service.bat manager .
The service automatically configures a private temporary directory for use by Elasticsearch when it is running. This private temporary directory is configured as a sub-directory of the private temporary directory for the user running the installation. If the service will run under a different user, you can configure the location of the temporary directory that the service should use by setting the environment variable ES_TMPDIR to the preferred location before you execute the service installation.
Most changes (like JVM settings) made through the manager GUI will require a restart of the service in order to take affect.
Directory layout of .zip archiveedit
The .zip package is entirely self-contained. All files and directories are, by default, contained within %ES_HOME% — the directory created when unpacking the archive.
This is very convenient because you don’t have to create any directories to start using Elasticsearch, and uninstalling Elasticsearch is as easy as removing the %ES_HOME% directory. However, it is advisable to change the default locations of the config directory, the data directory, and the logs directory so that you do not delete important data later on.
Type | Description | Default Location | Setting |
---|---|---|---|