-
Notifications
You must be signed in to change notification settings - Fork 0
/
elasticsearch.py
81 lines (67 loc) · 2.83 KB
/
elasticsearch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from pyspark import SparkContext
from pyspark.sql.context import SQLContext
from pyspark.sql.functions import array, col, collect_set, lit
from pyspark.sql.types import StringType, ArrayType, StructType, StructField
from argparse import ArgumentParser
from datetime import datetime, timedelta
import json
parser = ArgumentParser()
parser.add_argument("-en", "--esnodes", help="elasticsearch node. ex.192.168.18.50", dest="es_nodes", required=True)
parser.add_argument("-city", "--city", required=True)
parser.add_argument("-address", "--address", required=True)
parser.add_argument("-start_date", "--start_date", required=True)
parser.add_argument("-end_date", "--end_date", required=True)
args = parser.parse_args()
sc = SparkContext()
sqlContext = SQLContext(sc)
status = ['opening', 'closed']
def query(city, address, start_date, end_date):
elasticsearch_conf = {
"es.nodes": args.es_nodes,
"es.port": 9200,
"es.resource": "booking/_doc",
"es.mapping.date.rich": False,
"es.read.field.as.array.include": "tourists",
"es.read.field.include": "pageUrl, hotel, address, city, ratings, description, tourists, facility, created_time"
}
query = {
'_source': ['pageUrl, hotel, address, city, ratings, description, tourists, facility'],
'query': {
'bool': {
'must': [
{'term':{'city':city}},
{'exists': {'field': 'ratings'}},
{'match_phrase': {'address': address}},
{'range': {
'created_time': {
'gte': start_date, 'lte':end_date
}
}
}
]
}
}
}
schema = StructType([
StructField('pageUrl', StringType(), True),
StructField('hotel', StringType(), True),
StructField('address', StringType(), True),
StructField('city', StringType(), True),
StructField('ratings', StringType(), True),
StructField('description', StringType(), True),
StructField('tourists', ArrayType(StringType())),
StructField('facility', ArrayType(StringType()))
])
q = json.dumps(query)
df_all = sqlContext.read.format('es') \
.options(**elasticsearch_conf) \
.option('es.query', q) \
.schema(schema) \
.load()
df_all = df_all.groupBy('hotel').agg(collect_set('facility').alias('facilities'))
df_all = df_all.withColumn('status', array([lit(x) for x in status])))
df_all = df_all.filter(col('ratings') > 3)
df_all.printSchema()
return df_all
if __name__ == '__main__':
query(args.city, args.address, args.start_date, args.end_date)