37

I'm using elastisearch using Python. My code looks somewhat like this:-

from elasticsearch import Elasticsearch

if __name__ == '__main__': 
    index="IndexPosition"
    es=Elasticsearch(['https://localhost:8080'])
    res = es.search(index='{0}'.format(index), doc_type="log",size=1000, from_=0, body={ "query": {
    "match": {
      
        ...Match condition
      }
    }
  }})

Now, due to changes in architecture user authentication has been added in the elasticsearch.Let's assume username-user and password-pass.How do I pass the username and password in the query..?

buddemat
  • 4,552
  • 14
  • 29
  • 49
Mayank Jha
  • 939
  • 3
  • 12
  • 24

6 Answers6

62

You need to pass the username and password to the Elasticsearch object as shown below:

es = Elasticsearch(['http://localhost:8080'], http_auth=('user', 'pass'))

Dean Gurvitz
  • 854
  • 1
  • 10
  • 24
Girish kumar
  • 735
  • 6
  • 8
23

You can pass username, password in url:

ex:

username: elastic

password: changeme

es = Elasticsearch(hosts="http://elastic:changeme@localhost:9200/")

using CURL

curl -X GET "elastic:changeme@localhost:9200/"
Abhinav Keshri
  • 595
  • 5
  • 20
faisal burhanudin
  • 1,101
  • 12
  • 16
  • Why does *this* solution work for me, but not the one above (`http_auth=(user,pwd)`)? Also, saving passwords in clear text is fine for proof-of-concept, but I can't do this for the long term. Suggestions as to how to hide the password? – Guy Nov 09 '20 at 08:45
  • 1
    @Guy A common way of avoiding hardcoding credentials in the code is using environment variables. https://pypi.org/project/python-dotenv/ allows you to put credentials in a .env file and load them from there as environment variables – Jonáš Jančařík Jan 20 '22 at 14:39
3

In Elasticsearch 8.x, the http_auth parameter is deprecated, use basic_auth or bearer_auth respectively instead.

Elasticsearch >= 8.x basic auth example:

es = Elasticsearch(['https://localhost:8080'], basic_auth=('user', 'pass'))

Elasticseach < 8.x basic auth example:

es = Elasticsearch(['http://localhost:8080'], http_auth=('user', 'pass'))
buddemat
  • 4,552
  • 14
  • 29
  • 49
2
es = Elasticsearch([{'host': 'localhost', 'port': '8080'}], http_auth=('user', 'pass'))
ZeQun
  • 29
  • 1
2

yes, use es = Elasticsearch(hosts="http://username:password@es-endpoint:es-port/")

Test success in es version 7.7.1

em0t
  • 21
  • 3
  • hi, am getting an authentication error while trying to see if indices exists? Can you pls provide some sample code. Am using "res = esClient.indices.exists('metadata-store')" after creating esClient object with username/ password – Yuva Oct 19 '20 at 08:24
0

you can connect the elasticsearch with below Host url config

es = Elasticsearch(hosts="http://user:pass@localhost:9200/")
Hariharan AR
  • 1,386
  • 11
  • 20