Thursday, August 21, 2014

AzureSearch tutorial in ~100 lines of python

Here's a quick working sample of using AzureSearch with python. Please refer to readme in the comments for details on how to use it. It's pretty easy and basic stuff to get you started.



# Sample Python example to use AzureSearch
# **********************README***********************************
# Go to http://portal.azure.com and sign up for a search service.
# Get the service name and service key and plug it in below.
# This is NOT production level code. Please do not use it as such.
# You might have to install httplib2 if you're not already using it.
# ***************************************************************
import httplib2
import json

indexName = "adventurehotel"
serviceName = "azuresearch"
apiKey = '22CBC31568AAA84B243A63D36F555B85'

def getSampleDocumentObject():
    return {"value": [{
              "@search.action": "upload",
              "hotelId": "1",
              "baseRate": 199.0,
              "description": "Best hotel in town",
              "hotelName": "Fancy Stay",
              "category": "Luxury",
              "tags": ["pool", "view", "wifi", "concierge"],
              "parkingIncluded": False,
              "smokingAllowed": False,
              "lastRenovationDate": "2010-06-27T00:00:00Z",
              "rating": 5,
              "location": { "type": "Point", "coordinates": [-122.131577, 47.678581] }
            },
            {
              "@search.action": "upload",
              "hotelId": "2",
              "baseRate": 79.99,
              "description": "Cheapest hotel in town",
              "hotelName": "Roach Motel",
              "category": "Budget",
              "tags": ["motel", "budget"],
              "parkingIncluded": True,
              "smokingAllowed": True,
              "lastRenovationDate": "1982-04-28T00:00:00Z",
              "rating": 1,
              "location": { "type": "Point", "coordinates": [-122.131577, 49.678581] }
            },
            {
              "@search.action": "merge",
              "hotelId": "3",
              "baseRate": 279.99,
              "description": "Surprisingly expensive",
              "lastRenovationDate": None,
            },
            {
              "@search.action": "delete",
              "hotelId": "4"
            }]}

def getSampleIndexDefinition():
    return {
              "name": indexName,  
              "fields": [{"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False},
                {"name": "baseRate", "type": "Edm.Double"},
                {"name": "description", "type": "Edm.String", "filterable": False, "sortable": False, "facetable": False, "suggestions": True},
                {"name": "hotelName", "type": "Edm.String", "suggestions": True},
                {"name": "category", "type": "Edm.String"},
                {"name": "tags", "type": "Collection(Edm.String)"},
                {"name": "parkingIncluded", "type": "Edm.Boolean"},
                {"name": "smokingAllowed", "type": "Edm.Boolean"},
                {"name": "lastRenovationDate", "type": "Edm.DateTimeOffset"},
                {"name": "rating", "type": "Edm.Int32"},
                {"name": "location", "type": "Edm.GeographyPoint"}] 
            }

def getServiceUrl():
    return 'https://' + serviceName + '.search.windows.net/indexes/'

def getIndexUrl():
    return 'https://' + serviceName + '.search.windows.net/indexes/' + indexName

def getMethod(url):
    http = httplib2.Http()
    headers = {'api-key': apiKey, 
               'Host': serviceName + '.search.windows.net', 
               'Accept': 'application/json'}

    response, content = http.request(url, 'GET', headers=headers)
    print response, content
    return response, content

def postMethod(url, body):
    http = httplib2.Http()
    headers = {'Content-type': 'application/json', 'api-key': apiKey, 'Host': serviceName + '.search.windows.net'}
    response, content = http.request(url, 'POST', headers=headers, body=body)
    print response, content

def deleteMethod(url):
    http = httplib2.Http()
    headers = {'api-key': apiKey, 'Host': serviceName + '.search.windows.net'}
    response, content = http.request(url, 'DELETE', headers=headers)
    print response, content

def createSampleIndex():
    indexDefinition = json.dumps(getSampleIndexDefinition())    
    url = getServiceUrl() + "?api-version=2014-07-31-Preview"
    postMethod(url, indexDefinition)

def getSampleIndex():
    url = getIndexUrl() + '?api-version=2014-07-31-Preview'   
    getMethod(url)

def uploadSampleDocument():
    documents = json.dumps(getSampleDocumentObject())
    url = getIndexUrl() + '/docs/index?api-version=2014-07-31-Preview'   
    postMethod(url, documents)

def printDocumentCount():
    url = getIndexUrl() + '/docs/$count?api-version=2014-07-31-Preview'   
    getMethod(url)

def sampleQuery():
    url = getIndexUrl() + "/docs?search=*&$orderby=lastRenovationDate%20desc&api-version=2014-07-31-Preview"
    response, content = getMethod(url)

def deleteIndex():
    url = getIndexUrl() + "?api-version=2014-07-31-Preview"
    deleteMethod(url)

createSampleIndex()
getSampleIndex()
uploadSampleDocument()
printDocumentCount()
sampleQuery()
#deleteIndex()