Giter Club home page Giter Club logo

mixpanel-jql's Introduction

mixpanel-jql

PyPI Version Python Versions Coverage Build Status

A small Python library for running JQL queries against Mixpanel's JQL API. The data returned from the API is automatically decompressed as it arrives, making it available for processing as soon as the first row arrives. This is to avoid buffering large result sets in memory.

Installation

To install the mixpanel-jql library, simply run the following in your terminal:

pip install mixpanel-jql

Simple example

Let's do a simple count of our number of 'X' events over each day of May 2016. Our key for grouping will be the date the event was sent to Mixpanel in the format YYYY-MM-DD. We can get that from our event's time property by specifying our key as new Date(e.time).toISOString().split('T')[0].

This is simple and fast to do with this library.

from datetime import datetime
from mixpanel_jql import JQL, Reducer, Events

api_secret = '...'

query = JQL(
            api_secret,
            events=Events({
                'event_selectors': [{'event': "X"}],
                'from_date': datetime(2016, 5, 1),
                'to_date': datetime(2016, 5, 31)
            })
        ).group_by(
            keys=[
                "new Date(e.time).toISOString().split('T')[0]",
            ],
            accumulator=Reducer.count()
        )

for row in query.send():
    date = row['key'][0]
    value = row['value']
    print("[%s] => %d" % (date, value))
# [2016-05-01] => 302
# [2016-05-02] => 1102
# ...
# [2016-05-31] => 120

But what if we only want to count unique events? That is to say, what if we care about how many users spawned each event per day and not just the overall number of times the event occurred?

With some minor modification to our previous code, we can achieve this:

query = JQL(
            api_secret,
            events=Events({
                'event_selectors': [{'event': "X"}],
                'from_date': datetime(2016, 5, 1),
                'to_date': datetime(2016, 5, 31)
            })
        ).group_by_user(
            keys=[
                "new Date(e.time).toISOString().split('T')[0]",
            ],
            accumulator="function(){ return 1;}"
        ).group_by(
            keys=["e.key.slice(1)"],
            accumulator=Reducer.count()
        )

We replace our accumulator keyward argument with a JavaScript function returning 1, since each user will only be counted for once. group_by_user also adds the user ID into the key of our results. We can regroup our results by slicing that detail off with e.key.slice(1) and recounting.

More advanced examples

Let's assume we want to count all events 'A' with a property 'B' that is equal to 2 and a property F that is equal to "hello". Events 'A' also have a property 'C', which is some random string value. We want the results grouped and tallied by values of 'C' to see how many property 'C' events occurred over each day in the month of April 2016.

from mixpanel_jql import JQL, Reducer, Events

api_secret = '...'

query = JQL(
            api_secret,
            events=Events({
                'event_selectors': [{'event': "A"}],
                'from_date': '2016-04-01',
                'to_date': '2016-04-30'
            })
        ).filter(
            'e.properties.B == 2'
        ).filter(
            'e.properties.F == "hello"'
        ).group_by(
            keys=[
                "new Date(e.time).toISOString().split('T')[0]",
                "e.property.C"
            ],
            accumulator=Reducer.count()
        )

for row in query.send():
    date, c = row['key']
    value = row['value']
    print("[%s] %s => %d" % (date, c, value))
# [2016-04-01] abc => 3
# [2016-04-01] xyz => 1
# ...

If we wanted to count only unique events (i.e. count each user causing the event only once), we can change our query to group by user, to reduce the number of times they caused a particular e.properties.C to just 1.

query = JQL(
            api_secret,
            events=Events({
                'event_selectors': [{'event': "A"}],
                'from_date': '2016-04-01',
                'to_date': '2016-04-30'
            })
        ).filter(
            'e.properties.B == 2'
        ).filter(
            'e.properties.F == "hello"'
        ).group_by_user(
            keys=[
                "new Date(e.time).toISOString().split('T')[0]",
                "e.property.C"
            ],
            accumulator="function(){ return 1;}"
        ).group_by(
            keys=["e.key.slice(1)"],
            accumulator=Reducer.count()
        )

Why are your filters not joined with &&?

We could have also combined our .filter(...) methods into 1 method by doing, .filter('e.properties.B == 2 && e.properties.F == "hello"'). Successive .filter(...) expressions are automatically &&'ed. The method of expression you choose is stylistic.

What is that Reducer thing?

The Reducer class is for convenience and contains shortcuts to all the reducer functions (e.g. Reducer.count() returns mixpanel.reducer.count(), and Reducer.top(limit) returns mixpanel.reducer.top(limit)). Refer to the code for a list of all reducer shortcuts.

To write your own reducer, make sure to include a full JavaScript function body (i.e. function(){ ... }).

What about conversions?

The Converter class is another convenience for that.

from mixpanel_jql import Converter
...
Converter.to_number('"xyz"')  # Resolves to mixpanel.to_number("xyz")

What about queries over "people" and "joins"?

All of the previous examples are concerned primarily with JQL queries over events. This library also supports queries over people and the join of people and events. The following gives a skeleton for how that works.

You are free to use only one of events and people. join_params is only used if both events and people are set.

query = JQL(
            api_secret,
            events=Events({
                'event_selectors': [
                    {
                        'event': '...',
                        'selector': '...',
                        'label': '...'
                    },
                    ...
                ],
                'from_date': '<YYYY-MM-DD>',
                'to_date': '<YYYY-MM-DD>'
            }),
            people=People({
                'user_selectors': [
                    {
                        'selector': '...'
                    },
                    ...
                ]
            }),
            join_params={
                'type': 'full',
                'selectors': [
                    {
                        'event': '...',
                        'selector': '...',
                    },
                    ...
                ]
            }
        ). ...

What other functions are supported?

Mixpanel seems to be in a constant state of adding new functions beyond just filter and map. The following are presently supported by this library. Refer to the code for their usage.

  • filter
  • map
  • flatten
  • sort_asc
  • sort_desc
  • reduce
  • group_by
  • group_by_user

How do I see what the final JavaScript sent to Mixpanel will be?

Use str method on your JQL query to view what the equivalent JavaScript will be.

>>> str(query)
'function main() { return Events({"event_selectors": [{"event": "A"}], "from_date": "2016-04-01", "to_date": "2016-04-30"}).filter(function(e){return e.properties.B == 2}).filter(function(e){return e.properties.F == "hello"}).groupByUser([function(e){return new Date(e.time).toISOString().split(\'T\')[0]},function(e){return e.property.C}], function(){ return 1;}).groupBy([function(e){return e.key.slice(1)}], mixpanel.reducer.count()); }'

This can be quite helpful during debugging.

But what if you want something actually readable? That's now possible too with the .pretty method!

>>> print(query.pretty)
function main() {
    return Events({
        "event_selectors": [{
            "event": "A"
        }],
        "from_date": "2016-04-01",
        "to_date": "2016-04-30"
    }).filter(function(e) {
        return e.properties.B == 2
    }).filter(function(e) {
        return e.properties.F == "hello"
    }).groupByUser([function(e) {
        return new Date(e.time).toISOString().split('T')[0]
    }, function(e) {
        return e.property.C
    }], function() {
        return 1;
    }).groupBy([function(e) {
        return e.key.slice(1)
    }], mixpanel.reducer.count());
}

Caveats

.filter(...) automatically transforms whatever is within the parenthesis' into function(e){ return ... }.

To override that behavior, and use things like the properties.x shortcut syntax, use the raw(...) wrapper to insert whatever JavaScript you want into the filter, map .etc parameters.

from mixpanel_jql import JQL, raw
...
query = JQL(
            api_secret,
            events=params
        ).filter(
            raw(
                " function(e) {"
                "   if (e.x > 3) {"
                "     return true;"
                "   } else {"
                "     return false;"
                "   }"
                " )"
            )
        ).filter(
            'e.properties.F == "hello"'
        )
...

This library cannot easily express everything possible in Mixpanel's JQL language, but does try to simplify the general cases. If you have some ideas for making this library more user friendly to a wider range of potential queries, please submit a pull request or create an issue.

Contributions are very welcome!

Where can I learn more about Mixpanel's JQL?

For more information on what you can do with JQL, refer to Mixpanel's documentation here.

mixpanel-jql's People

Contributors

arawlin2 avatar omerlh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mixpanel-jql's Issues

Filter by words

Hello,

I am trying to export rows has logged out data.
There is current_url property and this include that information.
However, indexOf, slice, search, find, and include functions don't work.

query = JQL(
    api_secret,
    events=Events({
        'from_date': "2020-11-03",
        'to_date': "2020-11-03"
    })
).filter(
    'e.properties["current_url"].indexOf("loggedout") > -1  ' 
)

It will be helpful if these types of examples included.

How to sort a joined result from mixpanel?

function main() {
  return join(
    Events({
      from_date: "2017-01-01",
      to_date: "2018-01-15",
    }),
    People(),
    {
      type:"inner",
      selectors:[{selector:
        'user["$email"] == "..."'}]
    }
  )
  .sortAsc('event.time')
  .map(function (item) { return { name: item.event.name, page: item.event.properties['$current_url'], email: item.user.properties['$email'], time: item} });
}

Examples

It would be great to see some additional examples, particularly some examples that would 'out-of-the-box' work for even a most basic MixPanel setup. It would also be great if you could also pass arbitrary code to JQL, rather then JQL and associated functions always being used.

io.UnsupportedOperation: seek

In this portion:

for row in query.send():
    date = row['key']
    value = row['value']
    print("[%s] => %d" % (date, value))

It errors out with (only partial/tail end of the error):

"/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/lib/python2.7/gzip.py", line 296, in _read
self.fileobj.seek(0, 2)     # Seek to end of file                                                                                                                                           
io.UnsupportedOperation: seek

The query object is being saved (as a Mixpanel JQL object), and the send() function renders it as a generator send object, but iterating through it seems to cause problems. StackOverFlow says that seek(0, 2) (which means searching from the end of a document) is not supported in Python 2.7, and is only supported in Python 3+.

Any thoughts?

Filter not applied to Join

Hi
I have this:

params = {
    'from_date': '2016-06-01',
    'to_date': '2016-06-25'
}
query = JQL(api, params, people=True).filter('e.name == "Any event"')

print query.query_plan()

people=True makes a join between events and people, but when I apply the filter, such filter is applied only to events. How can I implement the filter for the join?.

If filter method is used, events=False and people=True arguments are ignored.

Thanks in advance.

An option on the JQL constructor to do an inner join on People and Events

The existing code if People and Events is true results in a full join, join(Events(params), People()).

Would be nice to have an option to do an inner join like this

join(Events(params), People(),{type:'inner'})

This can be used to avoid errors when the map function tries to read from an event that isn't present in the output of a full join.

Uncaught exception TypeError: Cannot read property 'time' of undefined
return {"distinct_id":e.distinct_id,"time":e.event.time
^
Stack trace:
TypeError: Cannot read property 'time' of undefined

Error on map function?

I received this error "AttributeError: 'JQL' object has no attribute 'raw_filter'"
after running this code
ret = '{"distinct_id":e.distinct_id}'
query = JQL(api_secret, params,events=True,people=True).map(ret)

I forked the repo and updated the map function so that this works, but wanted to make sure I was doing this correctly in the first place.

Add support for function in filter

It would be nice to support function as a filter argument. Currently this is not working because the library automatically added the return at the start of the filter, but we could add overload that do not do this.

mixpanel_jql.exceptions.InvalidJavaScriptText

Hi, first of all thanks for this project!

I'm trying to run the first example and I'm getting:
mixpanel_jql.exceptions.InvalidJavaScriptText: Must be a text type (str, unicode) or wrapped as raw(str||unicode)

I'm runnning Python 3.6.5 on Ubuntu 18.04

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.