Ver código fonte

only store search results if changed from previous runs

Martin 8 anos atrás
pai
commit
9744131399
2 arquivos alterados com 31 adições e 18 exclusões
  1. 3 0
      db_schema.py
  2. 28 18
      monitor.py

+ 3 - 0
db_schema.py

@@ -68,5 +68,8 @@ SCHEMA_STATEMENTS = [
         locality_id integer not null
     )
     ''',
+
+    'alter table search_results add column search_locality_id integer',
+    
     
 ]

+ 28 - 18
monitor.py

@@ -43,8 +43,6 @@ def process_properties(conn):
 
     _, _, locality_ancestors = get_locality_tree(conn)
 
-    
-
     print('Processing %i properties...' % count)
 
     rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 50')
@@ -58,9 +56,9 @@ def process_properties(conn):
             stmt += ' (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
 
             params.extend([
-                    property_id,
-                    last_update,
-                    raw_json,
+                property_id,
+                last_update,
+                raw_json,
             ])
 
             if raw_json is None:
@@ -161,14 +159,15 @@ def fetch_properties(conn):
 def search(conn, locality_id):
     logging.info('Searching %i...', locality_id)
     
-    cutoff = (datetime.datetime.now() - datetime.timedelta(hours=20)).strftime(_DATETIME_FORMAT)
-
-    recent_properties = set(conn.select('''select property_id from (select property_id, max(time) m 
-                                           from search_results group by property_id) where m > ?''', cutoff))
+    known_prices = conn.select('select property_id, max(time), price from search_results where search_locality_id=? group by property_id', locality_id)
+    known_prices = {row[0]: str(row[2]) for row in known_prices}
 
     page = 1
     num_pages = None
-    inserted = 0
+    added = 0
+    modified = 0
+
+    seen_properties = set()
 
     while True:
         config.SEARCH_PARAMS['RegionId'] = str(locality_id)
@@ -210,25 +209,35 @@ def search(conn, locality_id):
             print('Error: %s' % data)
             return
 
-        stmt = 'insert into search_results (time, property_id, price, raw_json) VALUES '
+        stmt = 'insert into search_results (search_locality_id, time, property_id, price, raw_json) VALUES '
         params = []
 
         for result in data.get('SearchResults', []):
             if not result.get('PriceAsString'):
                 continue
-            if result['id'] in recent_properties:
+
+            property_id = result['id']
+            price = result['PriceAsString'].replace(',', '').replace('\u20ac', '')
+
+            seen_properties.add(property_id)
+
+            if property_id in known_prices and known_prices[property_id] == price:
                 continue
 
-            stmt += '(?, ?, ?, ?),' 
+            stmt += ' (?, ?, ?, ?, ?),' 
 
             params.extend([
+                locality_id,
                 _now(), 
-                result['id'], 
-                result['PriceAsString'].replace(',', '').replace('\u20ac', ''),
+                property_id, 
+                price,
                 json.dumps(result)
             ])
 
-            inserted += 1
+            if property_id not in known_prices:
+                added += 1
+            else:
+                modified += 1
 
         if params:
             conn.execute(stmt[:-1], *params)
@@ -240,7 +249,9 @@ def search(conn, locality_id):
         
         page += 1
 
-    print('Search complete. %i records inserted.' % inserted)
+    gone = set(known_prices.keys()).difference(seen_properties)
+
+    print('Search complete. %i records fetched; %i new records added; %i records modified; %i records marked as gone.' % (len(seen_properties), added, modified, len(gone)))
 
 def run():
     with db.connect() as conn:
@@ -248,7 +259,6 @@ def run():
             for locality_id in config.MONITORED_LOCALITIES:
                 init_localities.init_localities(conn, locality_id=locality_id)
                 search(conn, locality_id)
-                pass
 
         else:
             print('You must set MONITORED_LOCATIONS. Possible values: ')